Java: 是否应将.close()放入finally块?

以下是关闭输出编写器的3种不同方式。第一个在try子句中放置close()方法,第二个在try子句中放置close,第三个使用try-with-resources语句。哪个是最合适的?

//close()在try子句中
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子句
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 (PrintWriter out2 = new PrintWriter(
			new BufferedWriter(
			new FileWriter("out.txt", true)))) {
	out2.println("the text");
} catch (IOException e) {
	e.printStackTrace();
}

回答

因为在任何情况下(异常或无异常)都应关闭Writer,所以close()应该放在finally子句中。
从Java 7开始,我们可以使用try-with-resources语句。

在这里插入图片描述

发布了16 篇原创文章 · 获赞 0 · 访问量 176

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105160350