'try with resource' feature for File class

谁都会走 提交于 2019-12-12 11:08:00

问题


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?


回答1:


 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




回答2:


You don't need to close a File because it's a pure Java object. It basically just holds the name of the file, nothing else (i.e. it does not require any OS resources to construct).

You only need to close your BufferedWriter and that is correctly AutocCloseable.




回答3:


You cannot create a BufferedWriter with File only, BufferedWriter requires a Writer, this how it should look like

    try (BufferedWriter w = new BufferedWriter(new FileWriter(new File("file")))) {
        ...
    }

try-with-resources will call close only on BufferedWriter. Unfortunately BufferedWriter API does say that it closes the underlying writer, but in fact it does. As for File it has nothing to do with try-with-resources since it is not Autocloseable.



来源:https://stackoverflow.com/questions/16337296/try-with-resource-feature-for-file-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!