Java Exception try-with-resources file closing

Introduction

Automatic resource management is based on the try statement.

Here is its general form:

try (resource-specification) {  
   // use the resource  
} 

Here, resource-specification declares and initializes a resource, such as a file stream.

The try-with-resources statement can be used only with those resources that implement the AutoCloseable interface.

The resource declared in the try statement is implicitly final.

The scope of the resource is limited to the try-with-resources statement.


import java.io.FileInputStream;

public class Main {
  public static void main(String args[]) {
    int i;/*from  w  w  w . ja  va  2s. c o m*/
    // a try-with-resources statement to open
    // a file and then automatically close it when the try block is left.
    try (FileInputStream fin = new FileInputStream("Main.java")) {

      do {
        i = fin.read();
        if (i != -1)
          System.out.print((char) i);
      } while (i != -1);

    } catch (Exception e) {
      System.out.println("An I/O Error Occurred");
    }

  }
}



PreviousNext

Related