Java中资源关闭的处理方式
2016-08-23 13:52
555 查看
本文就关于IO资源的处理问题,提出三种方案。
close()放在try块中
close()放在finally块中
使用try-with-resource语句
这种方式容易造成IO资源的泄露,因为对于IO资源来说不管操作的结果如何都必须关闭。
这种方式在
这种方式可能是最好的,Java官方推荐使用这种方式,但是,使用的前提是你的jdk版本在1.7以上。
如果使用jdk1.7以上的版本,推荐使用try-with-resources语句。
原文链接:should-close-be-put-in-finally-block-or-not
翻译:crane-yuan
[ 转载请保留原文出处、译者和译文链接。]
close()放在try块中
close()放在finally块中
使用try-with-resource语句
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(); }
这种方式容易造成IO资源的泄露,因为对于IO资源来说不管操作的结果如何都必须关闭。
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(); }
这种方式在
JDK1.7之前,推荐使用这种方式,但是,这种方式还是有问题,因为,在try块和finally块中可能都会发生Exception。
使用try-with-resource语句
//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(); }
这种方式可能是最好的,Java官方推荐使用这种方式,但是,使用的前提是你的jdk版本在1.7以上。
总结
因为不管什么情况下(异常或者非异常)资源都必须关闭,在jdk1.6之前,应该把close()放在finally块中,以确保资源的正确释放。如果使用jdk1.7以上的版本,推荐使用try-with-resources语句。
原文链接:should-close-be-put-in-finally-block-or-not
翻译:crane-yuan
[ 转载请保留原文出处、译者和译文链接。]
相关文章推荐
- Eclipse崩溃后无法启动的问题解决
- JAVA线程安全之synchronized关键字的正确用法
- java IO和NIO 的区别
- 重新开始学习javase_集合_List
- SpringMvc文件上传和下载
- springmvc json数据
- Java 基础
- JAVA中遇到 UTF-八 序列的字节 1 无效
- spring MVC之返回JSON数据(Spring3.0 MVC)
- Java mkdir() 导致的Bug
- Class对象和Java反射机制
- java base64加解密
- java反编译工具(JD-Eclipse) eclipse插件安装
- java HashTable
- JAVA 数据类型转换
- 华为OJ——计算日期到天数转换
- 支持Java的rest框架
- 使用Spring MVC的@ControllerAdvice注解做Json的异常处理
- Spring学习记录(三)---bean自动装配autowire
- Spring MVC 4.1 支持jsonp