close()方法应该在finally语句中调用吗?

翻译人员: 铁锚

翻译时间: 2013年12月20日

原文链接: Should .close() be put in finally block or not?

下面列出了关闭输出流(output writer) 的三种不同方式.

第一种是将close()方法调用置于try语句块内部;

//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();
	}
}

第三种是使用从Java 7 开始引进的 try-with-resources 方式;

//Java 7, 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 7 开始,我们也可以使用  try-with-resources  语句.

相关阅读:

  1. Top 10 Questions about Java Exceptions
  2. Merge Files in Java
  3. Java write to a file – code example
  4. Java code: Open IE browser and close it

原文地址:https://www.cnblogs.com/lanzhi/p/6467058.html