Automatic Resource Management

Java's try-with-resources statement automatically closes resources.

The try-with-resources statement consists of a try block:


try ([resource declaration; ...] resource declaration) 
{ 
    // code to execute 
}

The following example uses try-with-resources:


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copy {
  public static void main(String[] args) {
    try {
      copy("c:/a.txt", "c:/b.txt");
    } catch (FileNotFoundException fnfe) {
      String msg = "FileNotFoundException";
      System.err.println(msg);
    } catch (IOException ioe) {
      String msg = "IOException";
      System.err.println(msg);
    }
  }
  static void copy(String srcFile, String dstFile) throws IOException 
  { 
     try (
         FileInputStream fis = new FileInputStream(srcFile); 
         FileOutputStream fos = new FileOutputStream(dstFile)
     ) 
     { 
         int b; 
         while ((b = fis.read()) != -1) 
               fos.write(b); 
     } 
  } 

}

A try-with-resources statement can include catch and finally. These blocks are executed after all declared resources have been closed.

To take advantage of try-with-resources, a resource class must implement the java.lang.AutoCloseable interface or its java.lang.Closeable subinterface.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

class Main {
    final static String LINE_SEPARATOR = "\n";

    public static void main(String[] args) {
        String dest = "a.hex";
        try (FileInputStream fis = new FileInputStream(args[0]);
                FileOutputStream fos = new FileOutputStream(dest)) {

        } catch (IOException ioe) {
            System.err.println("I/O error: " + ioe.getMessage());
        }
    
    }
}

The following code auto close a Socket connection.


import java.io.InputStream;
import java.net.Socket;

public class Main  {

    public static void main(String[] args) {
        try (Socket socket = new Socket("yourTimeServer.com", 13)) {
            InputStream is = socket.getInputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (Exception ioe) {
            System.err.println("I/O error: " + ioe.getMessage());
        }
    }
}
Home 
  Java Book 
    Language Basics