Try With Resource block in java 7

 In Java, 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. 

This feature was introduced in Java 7.

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

public class TryWithResourcesExample {

    public static void main(String[] args) {

        // Path to the file to be read

        String filePath = "example.txt";

        // Using try-with-resources to ensure the BufferedReader is closed automatically

                 // FileReader::new with string filePath 

                // BufferedReade::new with FileReader which extends Reader interface

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {

       // Reading the file line by line

            String line;

       // readLine method of the BufferedReader reads a new line from the file and returns a             newLine from the file

        while ((line = br.readLine()) != null) {

                // Printing each line to the console

                System.out.println(line);

            }

        } catch (IOException e) {

           // Handling IOException

            e.printStackTrace();

        }

                    // Even after exception the Buffered Reader will be closed

                    // Both FileReader and BufferedReader implement the close() method

                    // and implement the AutoCloseable interface 

    }

}

Automatic Resource Management:

The BufferedReader and FileReader objects implement the AutoCloseable interface, 

which defines the close() method.

Java ensures that the close() method is called automatically on these resources at the end of the try block, even if an exception is thrown.

Exception Handling:

Any exceptions that occur during the reading of the file are caught in the catch block, where they are handled accordingly (in this case, printing the stack trace).

 


Comments

Popular posts from this blog

Hibernate Many to Many Relationship

Why Integral Calculus limit tending to infinity a sacrilege

Introduction