Thursday, May 29, 2014
Java 7 has introduced try-with-resources statement which ensures that resources (files or socket handles) declared in the statement are closed at the end of the statement. All objects implementing java.lang.AutoCloseable (AutoCloseable) can be used as a resource. Usage of try-with-resources ensures release of resources which otherwise would cause resource exhaustion and exceptions.

Prior to Java 7 resources are closed in the finally block. The finally block gets executed regardless of whether the try block completes successfully or not.

Let us consider a simple example to copy an input file to an output file prior to Java 7. In the implementation below FileInputStream and FileOutputStream are closed in the finally block.
public static void java6FileCopy() {
  FileInputStream fis = null;
  FileOutputStream fos = null;
  try {
    fis = new FileInputStream(new File("resources/input.txt"));
    fos = new FileOutputStream(new File("resources/output.txt"));
    int data = fis.read();
        while (data != -1)
        {          
            fos.write(data);
            data = fis.read();
        }
  } catch ( IOException e ) {
    e.printStackTrace();
  }
  finally {
    try {
      if ( fis != null ) fis.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      if ( fos != null ) fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
In Java 7 we can use the try-with-resources statement to declare the resources. This ensures that FileInputStream and FileOutputStream are automatically closed at the end of the try block.
public static void java7FileCopy() {
    try ( FileInputStream fis = new FileInputStream(new File("resources/input.txt"));
        FileOutputStream fos = new FileOutputStream(new File("resources/output.txt")); ) {
    int data = fis.read();
    while (data != -1)
    {          
        fos.write(data);
        data = fis.read();
    }
  } catch ( IOException e ) {
    e.printStackTrace();
  } 
}
Using try-with-resources makes the code more elegant and there is no need to close the resources explicitly.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top