Pages

Wednesday, November 27, 2013

Java 7 Tutorial - Try with Resources Example

In SE7 try/catch has been improved with the feature called try with resources option.
Normally when we use any resources (like File reader, Input stream etc) we need to close them explicitly to avoid performance penalties. Also you need to use finally block also in case if there are any exception happens before you close them.

For example when you try to read input from a file you normally code like this

/*
 * Normal try/catch block.
 */
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(
"c:\\tutorial\\HelloWorld.txt")));
String output = reader.readLine();
System.out.println("output :"+output);
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try {
if(reader != null)
{
System.out.println("finally block called :");
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

This is too much verbose and you have close the reader. If you forgot to close the reader then it unnecessarily blocks the resources and it will be a big performance bottleneck.

To avoid that SE 7 comes up with a feature called try with resources option. Here you open the resources with in try and once the code with in the try block completes, compiler automatically closes the opened resources so you dont have to close them explicitly.

try (BufferedReader reader1 = new BufferedReader(new FileReader(
new File("c:\\tutorial\\HelloWorld.txt")))) {
String output = reader1.readLine();
System.out.println("output in try with resource :"+output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Complete working example given below.

package com.ravi.java7learning;

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

public class Java7TryWithResources {

public static void main(String[] a)
{
Java7TryWithResources sample = new Java7TryWithResources();
sample.tryWithResourcesExample();
}

private void tryWithResourcesExample() {
/*
* Normal try/catch block.
*/
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(
"c:\\tutorial\\HelloWorld.txt")));
String output = reader.readLine();
System.out.println("output :"+output);
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try {
if(reader != null)
{
System.out.println("finally block called :");
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

try (BufferedReader reader1 = new BufferedReader(new FileReader(
new File("c:\\tutorial\\HelloWorld.txt")))) {
String output = reader1.readLine();
System.out.println("output in try with resource :"+output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

No comments:

Post a Comment

 
Blogger Templates