Search This Blog

Friday, 11 November 2016

Using the try-with-resources block

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

This approach enables a better programming style as it avoids nested and excessive try-catch blocks. It also ensures accurate resource management, which is referred to as
Automated Resource Management (ARM).

The following example illustrates the use of try-with-resource

    try (BufferedReader br = new BufferedReader(new FileReader(path))) 


In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java  7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly.


Prior to Java  7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.

You may declare one or more resources in a try-with-resources statement. 
The following code snippet illustrates one or more resources in a try-with-resources statement. 
try (
        ZipFile zf = new java.ZipFile(zipFileName);
       BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset)
    ) {
               // To – Do
               }


In the above example, the try-with-resources statement contains two declarations that are separated by a semicolon

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

public class Java7TryResource {

public static void main(String[] args) {
 try (BufferedReader br = new BufferedReader(new FileReader(
    "C:\\myfile.txt"))) {
   System.out.println(br.readLine());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment