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

简介: 翻译人员: 铁锚 翻译时间: 2013年12月20日 原文链接: Should .close() be put in finally block or not? 下面列出了关闭输出流(output writer) 的三种不同方式.

翻译人员: 铁锚

翻译时间: 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

目录
相关文章
|
11月前
每日一道面试题之try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
每日一道面试题之try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
144 0
|
4月前
|
编译器
try{...}catch(){...}finally{...}语句你真的理解吗?
try{...}catch(){...}finally{...}语句你真的理解吗?
32 0
try catch finally,try 里面有 return,finally 还执行吗?
try catch finally,try 里面有 return,finally 还执行吗?
50 0
|
4月前
|
Python
使用try-except-finally语句的例子。
使用try-except-finally语句的例子。
54 1
|
4月前
|
设计模式 消息中间件 前端开发
finally中的代码一定会执行吗?
finally中的代码一定会执行吗?
487 0
|
4月前
|
存储 缓存 IDE
细琢磨,try catch finally 执行顺序与返回值
细琢磨,try catch finally 执行顺序与返回值
52 0
|
存储 IDE Java
try catch finally 执行顺序总结
try catch finally 执行顺序总结
114 0
|
Java 数据库连接 数据库
try()catch{}自动释放资源
try()catch{}自动释放资源
216 0
try-catch-finally结构的finally语句 一定会执行吗? fianlly语句遇到System.exit(0);一定不执行吗?
try-catch-finally结构的finally语句 一定会执行吗? fianlly语句遇到System.exit(0);一定不执行吗?
159 0
try-catch-finally结构的finally语句 一定会执行吗? fianlly语句遇到System.exit(0);一定不执行吗?
|
NoSQL Java 数据库连接
finally 和 return,到底谁先执行
经常有人面试被问到:finally 和 return,到底谁先执行呢?