'try with resource' feature for File class
Solution 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
Solution 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
.
milind
Updated on June 19, 2022Comments
-
milind almost 2 years
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
andFile
, 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 theAutoCloseable
interface, butBufferedWriter
does. So how can I manage this scenario to implement 'try with resource' feature? -
milind about 11 yearsSo here you are saying that instead of creating a File object, I should directly pass the path of the file to the FileReader constructor and bypass the creation of File object.Right?
-
Vineet Singla about 11 yearsYes, Absolutely, FileWriter provides a constructor like public FileWriter(String fileName)throws IOException Constructs a FileWriter object given a file name.
-
milind about 11 yearsHow this will help. Are you saying here that if I create the File object the way you have specified then when the control moves out of the try block BufferedWriter, FileWriter as well as File will automatically be closed?
-
Vineet Singla about 11 yearsSee , this sample code :roseindia.net/java/beginners/java-write-to-file.shtml
-
Joachim Sauer about 11 years@milind: you can still use a
File
object, if you wish. You don't need to close that at all! -
Joachim Sauer about 11 years@milind: then please don't forget to upvote any answer that helped you solve it and accept the one that helped most.
-
milind about 11 years@ Joachim Sauer Ya thanks for reminding. I have upvoted on of the answer that helped me
-
Broken_Window over 9 yearsI was about to ask if a File object would left an opened file handle :)