在下面的代码中,close应该放在哪里?它应该在try语句还是finally语句中?如果终于,它是否应该与另一个尝试抓住?谢谢。我应该在哪里放置close()方法?
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter("out.txt", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
无论如何finally块都会被执行。所以我认为把它放在那里是正确的。 – sanket
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – HectorLector
如果使用1.7或更高版本,请使用['try-with-resources'](http://docs.oracle.com/javase /tutorial/essential/exceptions/tryResourceClose.html) – khachik