Java try-with-resources Close a Stream

Introduction

A stream must be closed when it is no longer needed.

You can use the following format to close a stream.

try {  
   // open and access file  
} catch( I/O-exception) {  
   // ...  
} finally {  
   // close the stream
}

Or we can use the try-with-resources statement.

The try-with-resources statement is an enhanced form of try that has the following form:

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

Here, resource-specification is a statement or statements that declares and initializes a resource.

Resources managed by try-with-resources must be objects of classes that implement AutoCloseable interface.

The resource declared in the try is implicitly final.

We can manage more than one resource by separating each declaration by a semicolon.

// Demonstrate FileInputStream. 
// This program uses try-with-resources. 
 
import java.io.FileInputStream;
import java.io.IOException;  
  
public class Main {  
  public static void main(String args[]) {  
    int size;  //from   w w  w . j  a v  a2 s  .co  m
  
    // Use try-with-resources to close the stream. 
    try ( FileInputStream f = 
           new FileInputStream("Main.java") ) { 
  
      System.out.println("Total Available Bytes: " +  
                         (size = f.available()));  

      for (int i=0; i < size; i++) {  
        System.out.print((char) f.read());  
      }  
 
      System.out.println("\nStill Available: " + f.available());  
    } catch(IOException e) {  
      System.out.println("I/O Error: " + e);  
    }  
  }  
}



PreviousNext

Related