Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'try with resource' feature for File class

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?

like image 211
milind Avatar asked May 02 '13 11:05

milind


2 Answers

 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

like image 73
Vineet Singla Avatar answered Oct 17 '22 18:10

Vineet Singla


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.

like image 32
Joachim Sauer Avatar answered Oct 17 '22 16:10

Joachim Sauer