Saturday, 21 July 2012

Try-With-Resources In JDK 7

In Java, normally we open a file in a try block, and close the file in the finally block, see following :

try{
  //open file or resources
}catch(IOException){
  //handle exception
}finally{
  //close file or resources
}
In JDK 7, a new “try-with-resources” approach is introduced. When a try block is end, it will close or release your opened file automatically.
try(open file or resource here){
 //...
}
//after try block, file will close automatically.
In JDK 6:
package com.sanjeetpaney.io;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example1 {
 
 public static void main(String[] args) {
 
  BufferedReader br = null;
 
  try {
 
   String line;
 
   br = new BufferedReader(new FileReader("C:\\testing.txt"));
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null)br.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 
 }
}
In JDK 7:
package com.sanjeetpandey.io;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class Example2 {
 
 public static void main(String[] args) {
 
  try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
  {
 
   String line;
 
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
 
  } catch (IOException e) {
   e.printStackTrace();
  } 
 
 }
}

No comments:

Post a Comment