Java 7 - AutoClosable Interface
Before java 7, we had to use finally blocks to cleanup the resources. Finally blocks were not mandatory, but resource clean up was to prevent the system from being corrupt. With java 7, there is no need to explicit resource cleanup. Its done automatically. Automatic resource cleanup is done when initializing resource in try-with-resources block (try(…) {…}).
Cleanup happens because of new interface?AutoCloseable. Its close method is invoked by JVM as soon as try block finishes. You are not supposed to call?close()?method in your code. This should be called automatically by JVM. Calling it manually may cause unexpected results.
public class ResourceManagementInJava7
{
????public static void main(String[] args)
????{
????????try (BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt")))
????????{
????????????String sCurrentLine;
????????????while ((sCurrentLine = br.readLine()) != null)
????????????{
????????????????System.out.println(sCurrentLine);
????????????}
????????}
????????catch (IOException e)
????????{
????????????e.printStackTrace();
????????}
????}
}