我在try / finally中关闭了文件,但代码分析警告我:
- Possible failure to close a FileOutputStream
- Possible failure to close a PrintWriter
- Possible failure to close an OutputStreamWriter
怎么会发生失败?如何确保FileStream已关闭?
public void writeFile(String filepath)
{
BufferedWriter bw = null;
PrintWriter pw = null;
try {
File file = new File(filepath);
bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
pw = new PrintWriter(bfw);
//do something
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
bfw.close();
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
解决方法:
How can failure happen?
看看你的finally块:
finally{
try{
bfw.close(); <== exception occured here
pw.close(); <== this is not execute
}catch(Exception e){
e.printStackTrace();
}
}
如果bfw.close()中发生异常怎么办? pw.close()永远不会执行.这导致资源泄漏.
How can I ensure the FileStream is closed?
有人已经指出最后使用try / catch / finally.
但如果你不喜欢看到这么多尝试捕获,我建议你使用像Apache Commons IO这样的库.
解:
try {
........
} finally {
IOUtils.closeQuietly(bfw);
IOUtils.closeQuietly(pw);
}
是的,如果使用Java 7或更高版本,您总是拥有try-with-resources.