Try-with-resources in java - java.lang.AutoCloseable interface - java7


Before java 7, we used to write explicit code for closing file in finally block by using try-finally block like this >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
   public static void main(String[] args) throws IOException {
          InputStream inputStream = null;
          try{
                 inputStream = new FileInputStream("c:/txtFile.txt");
                 //code......
          }finally{
                 if(inputStream!=null)
                 inputStream.close();
          }
   }
}



In java 7, using Try-with-resources >
  • we need not to write explicit code for closing file.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
  public static void main(String[] args) throws IOException {
         try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) {
             //code...
         }
  }
}
Note : Above program will execute properly provided file is found at specified directory.

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.



Using multiple resources inside Try-with-resources >
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...
          }
   }
}
Note : Above program will execute properly provided file is found at specified directory.



RELATED LINKS>



EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - detailed explanation with diagrams Set-1 > Q1- Q25


EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - 30 important OUTPUT questions Set-2 > Q26- Q60


No comments:

Post a Comment