Should we close both FileInputStream and BufferedInputStream ? OR BufferedReader and FileReader ?



Should be close both FileInputStream and BufferedInputStream ?  OR  BufferedReader and FileReader ?
Answer is big NO.



FileInputStream fis =  new FileInputStream("c:/myFile.txt");
BufferedInputStream bis =  new BufferedInputStream(fis);
     
//... code....

bis.close(); //close BufferedInputStream, it will close FileInputStream



BufferedInputStream is wrapper around FileInputStream and closing wrapper (i.e. BufferedInputStream) will close BufferedInputStream and FileInputStream as well.

Read : Read text from file using BufferedInputStream (and FileInputStream) in java file IO




When we Read text from file using BufferedReader's read() method in java file IO

FileReader fr = fr = new FileReader("c:/myFile.txt");;
BufferedReader br = new BufferedReader(fr);
    
//... code....

br.close(); //close BufferedReader, it will close FileReader
                


BufferedReader is wrapper around FileReader and closing wrapper (i.e. BufferedReader ) will close BufferedReader and FileReader as well.





Now lets move to java 7, and see how to deal with closing the Stream.

Before java 7, we used to write explicit code for closing file in finally block by using try-finally block.

In java 7, Using multiple resources inside Try-with-resources >
  • we need not to write explicit code for closing file.
  • Try-with-resources allows us to use multiple resources inside it, all that we need to do is separate resources by semicolon (;)
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
   public static void main(String[] args) throws IOException {
          try (InputStream inputStream = new FileInputStream("c:/txtFile.txt") ;
                InputStream bInputStream = new BufferedInputStream(inputStream) ){
                 //code...
          }
   }
}



Now, question comes why we need not to close file when we are using Try-with-resources?
Because FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interface’s close method automatically closes resources which are no longer needed.)

Which classes can be used inside Try-with-resources?
All the classes which implements AutoCloseable interface can be used inside Try-with-resources.


Read :Try-with-resources in java - java.lang.AutoCloseable interface




RELATED LINKS>

Read text from file using BufferedInputStream (and FileInputStream) in java file IO


Program to Read text from file in String using BufferedInputStream (and FileInputStream) in java file IO


Write String to file using BufferedWriter and FileWriter in java file IO

No comments:

Post a Comment