javacodex.com
Java Examples
Java Examples
memu home questions

Try With Resources Statement

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.

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

This java example reads the contents from a file. The BufferedReader is a resource that must be closed after the program is finished with it. Using Try With Resources takes care of it for us.

Source: (TryWithResources.java)

import java.io.*;
 
public class TryWithResources {
 
   public static void main( String[] args ) {
 
      String path = "/tmp/file.txt";
      try (BufferedReader br = new BufferedReader(new FileReader(path))) {
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      } catch(IOException e) {
      }
 
   }
}
 

Output:

$ java TryWithResources 
The cat in the hat

$ cat /tmp/file.txt 
The cat in the hat

Contact: javacodex@yahoo.com