Java 7 - try-with-resources

In this tutorial we will see about try-with-resources is a one of the fine feature added in Java 7.

For example if we need to allocate a resource for file handling or database connectivity then we need to explicitly close the resource which we have opened in our try block. In those cases it will be tedious to handle lot of resource management manually. In some of the cases we will have try with finally block where we will check for the resource closing. No matter whether the to resource has allocated or not finally block will be executed automatically for all time. Below is the simple example from earlier Java 7 as how we used to handle resources by using file handling.

In above program we can see explicitly programmers need to handle resource closing under finally block, whether resource has or not finally block will be executed compulsory. But in Java 7 onwards try-catch-resource feature introduced and programmer need not to worry about resource management once when we add resource in try statement as like bellow.

try(FileInputStreamfstream = new FileInputStream("test.txt")) {
.
.
}

Above statement will have same functionality of FileInputStream of our above program. Where as here resource closing close() method will be automatically called once try block completed. Even we can multiple resource under single try block as like below.