One of the Java 7 features is try-with-resources statement for automatic resource management. A resource is an object that must be closed once your program is done using that perticular resources, like a File resource or JDBC resource for database connection or a Socket connection resource.
Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement.
This approach used to cause memory leaks and performance hit when we forgot to close the resource. It is an important and required change in the java to enhance the security of the java application.
Hare is the template used before java 7.
try
{
//open resources like File, Database connection, Sockets etc
}
catch
(FileNotFoundException e) {
// Exception handling like FileNotFoundException, IOException etc
}
finally
{
// close resources
}
try
(
// open resources here){
// use resources
}
catch
(FileNotFoundException e) {
// exception handling
}
// resources are closed as soon as try-catch block is executed.
package r4rjdk7;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Java6ResourceManagement {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("D:\r4r.txt"));
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Java 7 resource management example:-package r4rjdk7;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Java7ResourceManagement {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader(
"C:\r4r.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}