Java Try With Resources

Try with resources was one of the Java 7 features which was meant for automatic resource management. Resources are objects which must be closed once your program has used them. Before Java 7 we used to use finally block to close such resources like closing Input streams, JDBC connections etc.

Let’s see a pseudo code snippet:

Before Java 7 you would open resource, catch possible exceptions and finally close/release the resource:

try{
	//open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
	// Exception handling like FileNotFoundException, IOException etc
}finally{
	// close resources
}

Java 7 try with resources implementation:

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
	// exception handling
}
// resources are closed as soon as try-catch block is executed.

This is the sample code for reading a file in Java 7. Here we are reading a single input stream resource which will get closed once try block is executed. This code is much more readable and has lesser number of lines of code:

public class Java7ResourcesExample {
 
	public static void main(String[] args) throws FileNotFoundException,
			IOException {
		try (BufferedReader br = new BufferedReader(new FileReader(new File(
				"c:\\downloads\\sample.txt")))) {
			String line = "";
			while ((line = br.readLine()) != null)
				System.out.println(line);
		}
	}
 
}

This is another example where we are opening multiple resources in a single line. We open a file resource to read from it and then write the content to another file resource. Resources are closed in reverse order to avoid dependencies

public class Java7ResourcesExample {
 
	public static void main(String[] args) throws FileNotFoundException,
			IOException {
		try (BufferedReader br = new BufferedReader(new FileReader(new File(
				"c:\\downloads\\sample.txt")));
				BufferedWriter wr = new BufferedWriter(new FileWriter(new File(
						"c:\\downloads\\sample2.txt")))) {
			String line = "";
			while ((line = br.readLine()) != null)
				wr.write(line);
		}
	}
 
}

We can also create a custom resource. For any resource to be used as try-resource it should be implementing the AutoCloseable interface and implement the close method.

public class Java7ResourcesExample {
 
	public static void main(String[] args) throws Exception {
 
		try(MyResource mr = new MyResource()){
			System.out.println("Inside Try");
		}
                System.out.println("Out of try-catch block.");
	}
 
}
 
class MyResource implements AutoCloseable {
 
	@Override
	public void close() throws Exception {
		System.out.println("Inside Close");
	}
}

The output of the above code would be:

Inside Try
Inside Close
Out of try-catch block

Mar Java Mit Java :),/strong>

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *