What is try-with-resources in Java 7 or above?
UPDATED: 25 April 2015
Tags:
Exception
Java designer has finally came up with better solution for closing resource. try-with-resources introduced in Java 7. Its one of noticeable feature of Java 7 and currently used by developers around the world.
The try-with-resources statement ensures that all your resources like BufferedReader, FileInputStream, ObjectInputStream, etc... closed at the end of statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Source Code
import java.io.BufferedReader; import java.io.FileReader; public class TryWithResourcesExample { public static void main(String[] args) { /** * Resources declared in parentheses `()` after `try` keyword * implements java.io.Closeable interface. * * Note: * - Even if exception occurs both the resources will be closed. * - close methods of resources are called in the opposite order of their creation. */ try( /* Create object of FileReader */ FileReader objFileReader = new FileReader("D:\\Dropbox\\Notes.txt"); /* Create object of BufferedReader using object of FileReader */ BufferedReader objBufferedReader = new BufferedReader(objFileReader); ){ /* Print the first line of file */ System.out.println(objBufferedReader.readLine()); }catch(Exception ex){ ex.printStackTrace(); } } }
Note
- - Even if exception occurs all resources will be closed.
- - close methods of resources are called in the opposite order of their creation.
Tags:
Exception
0 comments :