try with resources in Java7

This article explains try with resources statement introduced in JDK 7.

 

Automatic Resource Management

 

Prior to JDK 7, during file operations, programmers had to explicitly call close() to close the file once it was no longer needed.

 

JDK 7 added a new feature that automates resource management. This is known as Automatic Resource Management.

 

The advantage is that it prevents situations where a file or other resource is inadvertently not released after it is no longer needed.

 

This automatic resource management is based on the try with resources statement.

 

try with resources

 

The general form of try with resources statement is :

 

try ( resource-specification ) {

  // use the resource

}

Here, resource-specification is a statement that declares and initializes a resource.

 

It consists if a variable declaration in which the variable is initialized with a reference to be object being managed.

 

When the try block ends, the resource is automatically released.

 

The try-with-resources statement can only be used with resources that implement the AutoCloseable interface.

 

Here is an example of try-with-resources :

 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TryWithResources {

  public static void main(String[] args) {
    int i;
    try(FileInputStream fin = new FileInputStream("in.txt");
        FileOutputStream fout = new FileOutputStream("out.txt")){
      do{
        i = fin.read();
        if(i!=-1){
          System.out.println((char)i);
        }
      }while(i!=-1);
    }
    catch(IOException e){
      System.out.println("Exception : " + e);
    }
  }

}

 

Here, the scope of the resource declared in try statement is limited to the try-with-resources block.

 

Also, the resource declared in the try statement is implicitly final. That means we can’t assign to the resource after it has been created.

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags