Java 7: New Feature – automatically close Files and resources in try-catch-finally

Try with resources is a new feature in Java 7 which lets us write more elegant code by automatically closing resources like FileInputStream at the end of the try-block.

Old Try Catch Finally

Dealing with resources like InputStreams is painful when it comes to the try-catch-finally blocks. You need to declare the resources outside the try so that they are is accessible from finally, then you must initialize the variable to null and check for non-null when closing the resource in finally.

  File file = new File("input.txt");

   InputStream is = null;

   try {
     is = new FileInputStream(file);

     // do something with this input stream
     // ...

   }
   catch (FileNotFoundException ex) {
     System.err.println("Missing file " + file.getAbsolutePath());
   }
   finally {
     if (is != null) {
       is.close();
     }
   }

Java 7: Try with resources

With Java 7, you can create one or more “resources” in the try statement. A “resources” is something that implements the java.lang.AutoCloseable interface. This resource would be automatically closed and the end of the try block.

File file = new File("input.txt");

try (InputStream is = new FileInputStream(file)) {
  // do something with this input stream
  // ...
}
catch (FileNotFoundException ex) {
  System.err.println("Missing file " + file.getAbsolutePath());
}

Exception handling

If both the (explicit) try block and the (implicit) resource handling code throw an exception, then the try block exception is the one which will be thrown. The resource handling exception will be made available via the Throwable.getSupressed() method of the thrown exception. Throwable.getSupressed() is a new method added to the Throwable class since 1.7 specifically for this purpose. If there were no suppressed exceptions then this will return an empty array.

Reference

http://download.java.net/jdk7/docs/technotes/guides/language/try-with-resources.html

Related posts:

  1. New Java 7 Feature: String in Switch support
  2. 2 ways to convert Java Map to String
  3. How to configure multiple page.xml files in Seam 2.2
  4. How to automatically recover Tomcat from crashes
  5. Installing Java 7 on Mac OS X

4 comments to Java 7: New Feature – automatically close Files and resources in try-catch-finally

  • DINESH

    when use Java 7: Try with resources

    try-with-resources not applicable to variable type
    required: java.lang.AutoCloseable
    found: java.io.InputStream

  • girijas

    Hi Vineet,

    I have installed jdk1.7 at my e:\. i have already jdk1.6 and 1.5 in my machine at c:\.

    in path=c:\jdk1.6\bin;e:\jdk1.7\bin;.;
    classpath=c:\jdk1.6\lib;e:\jdk1.7\lib;.;

    in cmd prompt,

    E:\>java -version
    java version “1.7.0″
    Java(TM) SE Runtime Environment (build 1.7.0-b147)
    Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)

    E:\>set path=e:\javasdk1.7\bin;.;

    E:\>javac
    Error: Could not find or load main class com.sun.tools.javac.Main

    Pleae help me.

  • vineet

    Remove JDK 1.6 from both path and classpath and try again.

  • Michal

    .NET has it from the very beginning :-) .

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes