A *resource* is as an object that must be closed manually,
such as a java.io.InputStream, OutputStream, Reader, Writer, Formatter;
java.nio.Channel;java.net.socket; java.sql.Connection, Statement, ResultSet,
or java.awt.Graphics.
The *automatic resource management statement* is a form of the try statement
that declares one or more resources. The scope of these resource
declarations is limited to the statement. When the statement completes,
whether normally or abruptly, all of its resources are closed automatically.
*EXAMPLES*
SIMPLE EXAMPLE: Here is a static method to read the first line of a file,
demonstrating the minimal (nearly) correct code to release a single resource
today.
static String readFirstLineFromFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}
Unfortunately, if the readLine and close invocations both throw exceptions,
the latter exception supplants the former. The only practical way around
this today would to be to ignore any exception thrown by the close invocation.
While this might be reasonable in the case of a Reader or InputStream, it
would be disastrous for a Writer or OutputStream.
Here’s how it would look with an automatic resource management statement:
static String readFirstLineFromFile2(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
return br.readLine();
}
}
You may declare one or more resources in a try-with-resources statement.
like
try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)
The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
public static void viewTable(Connection con) throws SQLException {
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
try (Statement stmt = con.createStatement()){
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + ", " + supplierID + ", " + price +
", " + sales + ", " + total);
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
}
}
The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.
Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Advantage : The automatic resource management statement obviates the need for manual resource termination, which has proven ugly and error prone.
It could emit the code to suppress the uninteresting(second) exception in favor of the interesting(first) one with no effort on the part of the programmer, and no loss to the clarity of the program.
Like the for-each statement(introduced in java 1.5), the automatic resource management statement is a small piece of syntactic sugar with a very high power-to-weight ratio.
Disadvantage: Like all syntactic sugar, this construct removes a bit of java's "what you see is what you get" character ("transparency").
Excellent feature in java.... thank you for sharing.
ReplyDelete