Http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
The Try-with-resources Statement
The try
-with-resources statement is a try
statement this declares one or more resources. A Resource is as an object that must was closed after the program was finished with it. The try
-with-resources statement ensures the resource is closed at the end of the statement. Any object is implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
and can be used as a resource.
The following example reads the first line from a file. It uses an instance of BufferedReader
-read data from the file. Was a resource that must being closed after the program is BufferedReader
fini Shed with it:
With Try-with-resources, you can automatically turn off resources that implement the autocloseable or Closeable interface. For example, the following function automatically calls the Close method of Bufferdreader after the try statement finishes, regardless of whether the code it includes is performed properly or an exception occurs.
static string Readfirstlinefromfile (string path) throws IOException { try (bufferedreader br = new BufferedReader (New FileReader (path))) { return br.readline (); }}
In this example, the resource declared in the try
-with-resources statement is a BufferedReader
. The declaration statement appears within parentheses immediately after the try
keyword. The class bufferedreader
, In java Se 7 and later, implements the interface Java.lang.AutoCloseable
. Because the bufferedreader
instance is declared in a try
-with-resource statement, it'll be closed regardless of whether the try
Statement completes normally or abruptly (as a result of the method bufferedreader.readline
throwing an ioexception
).
Prior to Java SE 7, your can use a finally
block to ensure that a resource is closed regardless of whether the try
Statemen T completes normally or abruptly. The following example uses a finally
block instead of a try
-with-resources statement:
You can use the FINALLY clause to ensure that resources are closed before the try-with-resources occurs, such as the following method.
But one difference is that, in the Readfirstlinefromfilewithfinallyblock method, if an exception is thrown in the finally clause, the exception thrown in the try code block is suppressed.
Conversely, in the Readfirstlinefromfile method, if an exception is thrown in the close method of the open resource in the Try-with-resources statement and in the try code block, the exception thrown by the Close method is suppressed and the exception in the try code block is thrown.
In this regard, the last example can be seen.
static string Readfirstlinefromfilewithfinallyblock (string path) throws IOException { BufferedReader br = new BufferedReader (new FileReader (path)); try { return br.readline (); } finally { if (br! = null) Br.close ();} }
However, in this example, if the methods readLine
and Close
both Throw exceptions, then the method readfirstlinefromfilewithfinallyblock
throws the exception Thrown from the finally
block; The exception thrown from the try
block is suppressed. In contrast, in the example readfirstlinefromfile
, if exceptions is thrown from both the tr Y
block and the try
-with-resources statement, then the method Readfirstlinefromfile
throws The exception thrown from the try
block; The exception thrown from the try
-with-resources a block is suppressed. In the Java SE 7 and later, you can retrieve suppressed exceptions; See the section suppressed exceptions for more information.
Declare one or more resources in a try
-with-resources statement. The following example retrieves the names of the files packaged in the zip file and zipFileName
creates a text file that contain s the names of these files:
You can declare multiple resources in a try-with-resources statement, which are closed in the reverse order of the declarations, such as the following method.
public static void Writetofilezipfilecontents (String zipfilename, String outputfilename) throws Java.io.IOExcept Ion {Java.nio.charset.Charset charset = java.nio.charset.Charset.forName ("Us-ascii"); Java.nio.file.Path Outputfilepath = Java.nio.file.Paths.get (OutputFileName); Open zip file and create output file with Try-with-resources statement try (java.util.zip.ZipFile ZF = New Java.util.zip.ZipFile (Zipfilename); Java.io.BufferedWriter writer = Java.nio.file.Files.newBufferedWriter (Outputfilepath, CharSet)) {//Enu Merate each entry for (java.util.Enumeration entries = Zf.entries (); entries.hasmoreelements ();) {//Get the entry name and write it to the output file String newLine = System.getproperty ("Line.separator" ); String Zipentryname = ((java.util.zip.ZipEntry) entries.nextelement ()). GetName () + newLine; Writer.write (zipentryname, 0, Zipentryname.length ()); } } }
In this example, the try
-with-resources statement contains and the declarations that is separated by a semicolon: and ZipFile
BufferedWriter
. When the block of code is directly follows it terminates, either normally or because of an exception, the close
methods Of the BufferedWriter
and ZipFile
objects is automatically called in this order. Note that the close
methods of resources is called in the opposite order of their creation.
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, SAL ES, 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 used in this example are part of the java.sql.Statement
JDBC 4.1 and later API.
Note: A try
-with-resources statement can has catch
and finally
blocks just like an ordinary try
statement. In a try
-with-resources statement, any catch
or finally
block are run after the resources declared has been closed.
Note: A try-with-resources statement can also have catch and finally clauses. The catch and finally clauses are called after the resource opened in the Try-with-resources clause is closed.
Suppressed Exceptions
An exception can is thrown from the block of code associated with thetry
-with-resources statement. In the examplewriteToFileZipFileContents
, an exception can is thrown from thetry
block, and up to both exceptions can thrown from thetry
-with-resources statement when it tries to close theZipFile
andBufferedWriter
Objects. If an exception are thrown from thetry
Block and one or more exceptions is thrown from thetry
-with-resources statement, then those exceptions thrown from thetry
-with-resources statement was suppressed, and the exception thrown by the block is the the one that's thrown by thewriteToFileZipFileContents
Method. You can retrieve these suppressed exceptions by calling theThrowable.getSuppressed
Method from the exception thrown by thetry
Block.
Note: As mentioned earlier, if an exception is thrown in the close method of the open resource in the Try-with-resources statement and in the try code block, the exception thrown by the Close method is suppressed and the exception in the try code block is thrown.
After Java7, the suppressed exception can be obtained using the Throwable.getsuppressed method.
Classes that Implement the autocloseable or closeable Interface
See the Javadoc of the AutoCloseable
and Closeable
interfaces for a list of classes that implement either of these interfaces. The Closeable
interface extends the AutoCloseable
interface. The close
method of the Closeable
interface throws exceptions of type while the method of the IOException
close
AutoCloseable
interface Throw s exceptions of type Exception
. Consequently, subclasses of the AutoCloseable
interface can override this behavior of the close
method to throw specialized EXCEP tions, such as IOException
, or no exception at all.
Example
[Java]View PlainCopy
- Import java.io.Closeable;
- Import java.io.IOException;
- Public class Dummyclosable implements Closeable {
- Private Final Boolean throwinclose;
- Private final String name;
- Public dummyclosable (boolean throwinconstruction, boolean throwinclose, String name) throws IOException {
- this.throwinclose = throwinclose;
- this.name = name;
- if (throwinconstruction) {
- throw New IOException ("throwing in construction");
- }
- }
- @Override
- public Void Close () throws IOException {
- if (throwinclose) {
- throw New IOException ("throwing in close");
- }
- SYSTEM.OUT.PRINTLN (name + "is closing ...");
- }
- public static void Main (string[] args) {
- try (dummyclosable d1 = new Dummyclosable (false, false, "a");
- Dummyclosable D2 = new Dummyclosable (true, false, "B");) {
- throw New IOException ("in Main1");
- } catch (Exception ex) {
- Ex.printstacktrace (System.out);
- }
- System.out.println ("----end1----");
- try (dummyclosable d1 = new Dummyclosable (false, false, "a");
- Dummyclosable D2 = new Dummyclosable (false, true, "B");) {
- throw New IOException ("in Main2");
- } catch (Exception ex) {
- Ex.printstacktrace (System.out);
- }
- System.out.println ("----end2----");
- }
- }
Running the above example, the results are as follows:
[Plain]View PlainCopy
- A is closing ...
- Java.io.IOException:throwing in construction
- At Learning.io.dummyclosable.<init> (dummyclosable.java:14)
- At Learning.io.DummyClosable.main (dummyclosable.java:28)
- ----END1----
- A is closing ...
- Java.io.IOException:in main2
- At Learning.io.DummyClosable.main (dummyclosable.java:37)
- Suppressed:java.io.IOException:throwing in close
- At Learning.io.DummyClosable.close (dummyclosable.java:21)
- At Learning.io.DummyClosable.main (dummyclosable.java:38)
- ----END2----
http://blog.csdn.net/fw0124/article/details/49946975
Java7 New Grammar-try-with-resources