Monday, 5 January 2015

TRY-WITH-RESOURCES Statement in Java 7

In java 7, try statement has been enhanced.

Whenever if some resource is used it must be closed once its use is completed.

So, conventionally a developer must need to close the resources -say a database resource, a file handler and any such resource.

generally, this is done in "finally" 

Example:

using try statement - before java 7

...

static String readMe( String path) {

    BufferedReader br = new BufferedReader ( new FileReader(path) );

    try{
             return br.readLine();

    }
   finally
   {
          if( br != null ) 
                br.close();
   }


}

...

With java 7, you as a developer no need to close the resources. But you must use try-with-resources statement instead of normal try statement.

A try-with-resource statements has an open bracket '(' and a closed bracket ')' and in between these brackets you must declare the resource.

Example:

...

static String readMe( String path) {

   try ( BufferedReader br = new BufferedReader( new FileReader(path) ) ){

            return br.readLine();
   }

}

...

Note:


You can close the resources using try-with-resources statement in java 7 for any class that implements either AutoCloseable interface or Closeable interface.

Classes that implements AutoCloseable interface - Click Here

Classes that implements Closeable interface - Click Here


Here, the BufferedReader class implements AutoCloseable interface.

Regardless of whether the try statment executes nomally or Abruptly , the resource will be closed.

Note:

You can declare as many resources separating them with semi-colon.

Example:

....

try ( java.util.jar.JarFile jr = 
                        new java.util.jar.JarFile(jarFileName) ;
        java.util.zip.ZipFile zp =
                       new java.util.zip.ZipFile(zipFileName)
   ) 
{


 ...// create a jar file logic & zip file logic



// once the execution completes - resources jar and zip file handler are also
closed automatically since they implement AutoCloseable interface.


Hope this gives a brief intro.
Please share this.