为File类尝试使用资源功能 [英] 'try with resource' feature for File class

查看:156
本文介绍了为File类尝试使用资源功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我试图用Java 7'试用资源'功能来实现。

我的finally块包含一个 BufferedWriter File ,我想关闭使用尝试与资源功能,而不是通过显式调用close方法关闭它。

但是我在网上查了一下,看到 File 类没有实现 AutoCloseable 接口,但是 BufferedWriter 没有。那么如何管理这个场景来实现试用资源功能?

解决方案

try(BufferedWriter br = new BufferedWriter(new FileWriter(path)))

使用这个简单的br会自动关闭。
例如。 http://www.roseindia.net/java/beginners/java -write-to-file.shtml


I have one scenario where I am trying to implement with the Java 7 'try with resource' feature.

My finally block contains an object of BufferedWriter and File, which I want to close using 'try with resource' feature, instead of closing it by calling close method explicitly.

But I checked on net and saw that the File class does not implement the AutoCloseable interface, but BufferedWriter does. So how can I manage this scenario to implement 'try with resource' feature?

解决方案

 try (BufferedWriter br = new BufferedWriter(new FileWriter(path))) 

Use this simply, br will be closed automatically. Eg. http://www.roseindia.net/java/beginners/java-write-to-file.shtml

这篇关于为File类尝试使用资源功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆