我们知道,无论是在操作系统底层,还是对于JVM而言,文件都是一种非常昂贵的资源,如果不能正确地关闭,严重时,可能导致应用的崩溃。在仔细观察和分析各种Java的开源库之后,发现,Java程序员具有三种常见的关闭文件的方式。第一种是把 close() 方法放在了 try 语句块中,第二个方式把 close() 方法放在了 finally 语句块中,第三种使用了JDK7中引入的 try-with-resource 语句。那么,哪一个才是正确的,最好的呢?
示例代码
//close() is in try clause
try {
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
//close() is in finally clause
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
//try-with-resource statement
try (PrintWriter out2 = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)))) {
out2.println("the text");
} catch (IOException e) {
e.printStackTrace();
}
总结
上述的三种方式中,第一种是错误的。因为,第一种方式不能够在文件操作出现异常时正确关闭文件,所以应该把 close() 方法放在 finally 语句块中。第三种方式其实是Java对于第一种方式提供的语法糖,从JDK7开始,建议使用更加简洁的第三种方式。