'try with resource' feature for File class

11,190

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.

Share:
11,190
milind
Author by

milind

Updated on June 19, 2022

Comments

  • milind
    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 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?

  • milind
    milind about 11 years
    So 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
    Vineet Singla about 11 years
    Yes, Absolutely, FileWriter provides a constructor like public FileWriter(String fileName)throws IOException Constructs a FileWriter object given a file name.
  • milind
    milind about 11 years
    How 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
    Vineet Singla about 11 years
  • Joachim Sauer
    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
    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
    milind about 11 years
    @ Joachim Sauer Ya thanks for reminding. I have upvoted on of the answer that helped me
  • Broken_Window
    Broken_Window over 9 years
    I was about to ask if a File object would left an opened file handle :)