Sunday, February 2, 2014

Java example using try-with-resources

Source:
import java.io.*;
 
public class TryWithResources {
 
   public static void main( String[] args ) {
 
      String path = "/tmp/file.txt";

      // No need to close the BufferedReader
      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