有三种不同的方式关闭输出写入器。第一种将close()语句放在try子句方法里面,第一种在try子句中放置close()方法,第二个放在finally子句中,第三个使用try-with-resources语句,哪个是最正确?
//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 放在finally里面。
//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();
}
答案
因为Writer必须在任何情况下被关闭(异常情况或非异常情况),close()应该在finally被关闭。