try-with-resources
is an interesting concept in java. The purpose of this is to auto dispose/close the resource as soon as it serves its purpose.
For instance in Java 6 and below, a buffer reader is initialized and closed manually in try's finally block.
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Now, with try-with-resources
, (started supported BufferedReader from Java 7) it is automatically closed as soon the try statement block executes completely. It closes automatically, irrespective of success or error of try block.
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
Note: java.lang.AutoCloseable
must be implemented for any class to support try-with-resources.
Hope this helps.