Java 7 Try with Resources Statement

In the pre Java 7 world, you would typically acquire and use resources inside a try block, handle exceptions in the catch block(s) and release the resources in the finally block. The finally block is always executed irrespective of whether exceptions occur or not. The Java 7 try with resources statement eliminates the need for finally block for resource management. You can do so by declaring your resources in the brackets following the token try.

Here is a sample program with try-with-resources statement:

package com.quicklyjava;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Java7TryDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String path="c:/test.txt";
		
		try(BufferedReader br1 = new BufferedReader(new FileReader(path))){
			System.out.println(br1.readLine());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

A few point to note:

1) You can have multiple resources declared in the try, e.g.

Around The World Flights - Promo Code WORLD15
try(	BufferedReader br1 = new BufferedReader(new FileReader(path));
				BufferedReader br2 = new BufferedReader(new FileReader(path));)

2) The resources managed in this statement should implement java.lang.AutoCloseable or java.io.Closeable interface. So basically this statement can take care of your custom resources as well as long as it implements one of these interfaces.

Thus you can effectively use in Java 7 try with resources statement for Automatic Resource Management.

You can download the eclipse project of the code explained in this tutorial:
Java7TryDemo.zip (3K)

One response to “Java 7 Try with Resources Statement”

  1. Chavy

    In your example, you shuold make sure to close the BufferedReader, otherwise the file may be lock not readable by some other process.so . while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); }br.close(); ..

Leave a Reply