关闭 Java FileInputStream [英] Closing a Java FileInputStream
问题描述
好的,我一直在做以下事情(变量名已更改):
Alright, I have been doing the following (variable names have been changed):
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
... process ...
}
catch (IOException e)
{
... handle error ...
}
finally
{
if (fis != null)
fis.close();
}
最近,我开始使用 FindBugs,这表明我没有正确关闭流.我决定看看是否有任何可以用 finally{} 块完成的事情,然后我看到,哦,是的,close() 可以抛出 IOException.人们应该在这里做什么?Java 库抛出太多已检查的异常.
Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions.
推荐答案
对于 Java 7 及更高版本 try-with-resources 应该被使用:
For Java 7 and above try-with-resources should be used:
try (InputStream in = new FileInputStream(file)) {
// TODO: work
} catch (IOException e) {
// TODO: handle error
}
如果您坚持使用 Java 6 或更低版本...
If you're stuck on Java 6 or below...
这种模式避免了使用 null 的麻烦:
This pattern avoids mucking around with null:
try {
InputStream in = new FileInputStream(file);
try {
// TODO: work
} finally {
in.close();
}
} catch (IOException e) {
// TODO: error handling
}
<小时>
有关如何有效处理close的更多详细信息,请阅读这篇博文:Java:如何不把流处理弄得一团糟.它有更多示例代码、更深入,并涵盖了将 close 包装在 catch 块中的陷阱.
For a more detail on how to effectively deal with close, read this blog post: Java: how not to make a mess of stream handling. It has more sample code, more depth and covers the pitfalls of wrapping close in a catch block.
这篇关于关闭 Java FileInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!