try with resources statement in JDK7

try with resources statement in JDK7

Before Java 7 if you open a resource like file or DBconnection in try block,you need to close the resource in finally block externally. like below
With out try-with-resources
try{
//exception handling code
}catch(Exception e)
//open any resource like File or DB Connection
{

}finally{
//closing The resource like closing the DB connection or file closing
}
Example
package com.java2study.practice;

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

public class Test {

public static void main(String[] args) {
BufferedReader br = new BufferedReader(new FileReader("c:\\java2study.txt"));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
}

The try-with-resources statement is a new feature added in Java 7. according to this if we open any resource like file or DBconnection in try block that resource is closed at the end of the try statement.
In JDK7 we got try-with-resources statement feature it guarantees that each resource is closed at the end of the try statement. which means if you open any resource(File) in try block you no need to close the resource(file) in finally block explicitly the resource will close automatically at the end of try statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Syntax
 try (resource path goes here) {
//statements
}
}

Example

package com.java2study.practice;

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

public class Test {

public static void main(String[] args) {
try (BufferedReader br =
new BufferedReader(new FileReader("C:\\java2study.txt"))) {
return br.readLine();
}
}

}
if we use try-with-resources there is no need to use finally block to close connections.

we can use Multiple resources in try-with-resources .we can separate multiple resource by using semicolon(;). see the snippet below
 try(java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset))


-->