关闭Java FileInputStream [英] Closing a Java FileInputStream
问题描述
好的,我一直在做以下(变量名已经改变):
FileInputStream fis =空值;
try
{
fis = new FileInputStream(file);
...进程...
}
catch(IOException e)
{
...句柄错误...
}
finally
{
if(fis!= null)
fis.close();
}
最近,我开始使用FindBugs,这表明我是没有正确关闭流。我决定看看是否有任何可以完成的最终{}块,然后我看到,哦,close()可以抛出IOException。人们应该在这里做什么? Java库引起太多的检查异常。
对于Java 7及更高版本 try-with-resources :
try(InputStream in = new FileInputStream(file)){
// TODO:work
} catch(IOException e){
// TODO:handle错误
}
如果你坚持Java 6或更低版本...
此模式避免了使用 null :
try {
InputStream in = new FileInputStream(file);
try {
// TODO:work
} finally {
in.close();
}
} catch(IOException e){
// TODO:错误处理
}
有关如何有效处理关闭的更多详细信息,请阅读此博文: Java:如何不让乱码流处理。它具有更多的示例代码,更深入的内容,并涵盖了关闭在 catch 块中的陷阱。
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();
}
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.
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
}
If you're stuck on Java 6 or below...
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
}
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屋!