Often we use the try block while using resources like Streams and Connections. In these cases it is mandatory to close the resources after the completion of the task. We usually do the same in the finally block as in the example below
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
In Java 7 this process has been shortened by the try-with-resource statement. In this the resources are implicitly closed on the completion of the try fragment irrespective of whether the code was successfully executed or with exception. The only change is that the resource must implement the java.lang.AutoCloseable interface. The classes java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement.
No comments:
Post a Comment