【发布时间】:2012-12-03 04:58:48
【问题描述】:
所以。我正在尝试在 Android 上做一些网络工作。在我的异步任务中,我正在做:
InputStream streamOfDestiny = null;
try{
// do some network stuff here...
}
finally{
if(streamOfDestiny != null){
streamOfDestiny.close(); // Build error here. Apparently, closing a stream can cause an IOException. Why this is the case, I do not know. But it is. And, since this is Java, I apparently need to care.
}
}
所以现在我得到了这个 IOException 把一切都搞砸了。我可以这样做:
InputStream streamOfDestiny = null;
try{
// do some network stuff here...
}
finally{
if(streamOfDestiny != null){
try{
streamOfDestiny.close();
}
catch(IOException e){
// Hey look! I'm inside a catch block, inside a finally block!
}
}
}
但这看起来很糟糕。 finally 块中的 try/catch 块?多么丑陋!我完全可以让它保持关闭状态,但这对我来说似乎是一种不好的做法,而且感觉不对(我开始直播,我想完成它)。我可以这样做:
IOUtils.closeQuietly(streamOfDestiny);
但现在我必须找到 org.apache.commons.io.IOUtils 并以某种方式将其包含到我的包中。太多的工作,加上我只需要一个功能的东西增加了我的包大小。跛脚。
我总是可以编写自己的 closeQuietly 版本:
public static void closeStreamQuietly(InputStream streamToClose){
try{
streamToClose.close();
}
catch (IOException e){
// ignore it....
}
}
但这似乎是我在重新发明轮子,这几乎总是坏消息——感觉应该有一些不错的、优雅的方式来做这件事,而我在这里完全错过了。
各位有什么想法吗?
【问题讨论】:
标签: java android inputstream