Wednesday, 3 January 2018

Core java | try with resource Statement in Java

In Java 6, we open a file in a try block and close the file in the finally block

try {
      //open file or resources
catch(IOException) {
      //handle exception
finally {
      //close file or resources
}

Disadvantages
1. You'd have to check if your resource is null before closing it.
2. The closing itself can throw exceptions so finally had to contain another try – catch.
3. Programmers tend to forget to close their resources.

In JDK 7, a new “try-with-resources” approach is introduced.
When a try block is an end, it will close or release your opened file automatically.

try(open file or resource here) {
      //...
}
//after try block, file will close automatically.

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.

Example
import java.util.Scanner;

class Demo {
     public static void main(String[] args) {

           try(Scanner scan=new Scanner(System.in)) {
                String str = scan.next();
                System.out.println(str);
           }
     }
}

Benefits of using try with resources
1. Automatic resource management.
2. More readable code and the number of lines of code is reduced.
3. No need to have finally block just to close the resources.
4. We can open multiple resources in try-with-resources statement separated by a semicolon.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));   
     Scanner scan = newScanner(System.in))) {

      System.out.println(br.readLine());
catch (IOException e) {
      e.printStackTrace();
}

5. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue.

Note for Point#5

We can extend the resource program to prove that.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...