The try-with-resource Statement

In this section, you will learn about newly added try-with-resource statement in Java SE 7.

The try-with-resource Statement

In this section, you will learn about newly added try-with-resource statement in Java SE 7.

The try-with-resource Statement

The try-with-resource Statement

In this section, you will learn about newly added try-with-resource statement in Java SE 7.

The try-with-resource statement contains declaration of one or more resources. As you know, prior to Java SE 7, resource object must be closed explicitly, when the resource use or work is finished. After the release of Java SE 7, the try-with-resource statement handles it implicitly means it automatically closed the resource when it has no longer use to the class. But for this, you need to declare resources using try-with-resource statement.

Given below the code for the above :

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

public class J7TryWithResource {
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
System.out.println(br.readLine());
return br.readLine();
}
}

public static void main(String args[]) {
try {
readFirstLineFromFile("C://J7Try.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT

C:\Program Files\Java\jdk1.7.0\bin>javac J7TryWithResource.java

C:\Program Files\Java\jdk1.7.0\bin>java J7TryWithResource
HI !! FOLKS...WELCOME 2 DEVMANUALS !!

Download Source Code