Java NIO Try
-with-resources [reprint]
@ Original link http://blog.csdn.net/jackiehff/article/details/17765909
try
The-with-resources statement is a statement that declares one or more resources try
. A resource, as an object, must be closed after the program ends. The try
-with-resources statement ensures that every resource at the end of the statement is closed. Any implementation java.lang.AutoCloseable的对象
, including all implementations java.io.Closeable 的对象
, can be used as a resource.
The following example reads the first line of the file. It uses BufferedReader
an instance to read the data in the file. BufferedReader
is a resource that must be closed after the program ends:
1 static String Readfirstlinefromfile (String path) throws 2 try ( BufferedReader br = new BufferedReader (new FileReader (path)) { 3 return Br.readline (); 4 5 }
In this example, the try
-with-resources statement declares the resource to be one BufferedReader
. The declaration statement is immediately try
inside the parentheses of the keyword. In Java SE 7 and later BufferedReader类实现了
java.lang.AutoCloseable接口
. Because the BufferedReader
instance is try
declared in the-with-resource statement, either the try
statement is completed normally or an accident occurs (the result is that the Bufferedreader.readline method throws IOException), Buffer Edreader will be closed.
Before Java SE 7, blocks can be used finally
to ensure that resources are shut down, whether the try
statements are completed properly or if they occur unexpectedly. The following example finally
replaces the-with-resources statement with a block try
:
1 staticthrows IOException {2 new BufferedReader (new FileReader (path)); 3 try {4 return br.readline (); 5 finally {6 ifnull) br.close (); 7 }8 }
View Code
However, in this example, if the readLine
and close
method throws an exception, then the readFirstLineFromFileWithFinallyBlock
method throws finally
an exception thrown from the block; try
the exception thrown in the block is suppressed. Conversely, readFirstLineFromFile 这个例子中
if try
both the block and the try
-with-resources statement throw an exception, the exception thrown readFirstLineFromFile
from try
the block is thrown; try
the exception thrown by the-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions, see suppressed Exceptions for details.
You can try
declare one or more resources in a-with-resources statement . The following example retrieves the names of all the files in the zip file zipFileName
and creates a text file that contains those file names:
1 Public Static voidwritetofilezipfilecontents (String zipfilename, string outputfilename)2 throwsjava.io.IOException {3 4Java.nio.charset.Charset charset = java.nio.charset.Charset.forName ("Us-ascii");5Java.nio.file.Path Outputfilepath =Java.nio.file.Paths.get (outputfilename);6 7 //Open zip file and create output file with Try-with-resources statement8 9 Try (TenJava.util.zip.ZipFile ZF =NewJava.util.zip.ZipFile (zipfilename); OneJava.io.BufferedWriter writer =Java.nio.file.Files.newBufferedWriter (Outputfilepath, CharSet) A ) { - - //Enumerate each entry the - 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; AWriter.write (zipentryname, 0, Zipentryname.length ()); at } - } -}
View Code
In this example, the try
-with-resources statement contains two declarations separated by semicolons: ZipFile
and BufferedWriter
. When the code block is directly accompanied by it normally or due to an abnormal termination, BufferedWriter
and the ZipFile 对象的
close
method is called automatically in this order. Note: The method invocation order of the resources is the close
opposite of the order in which they were created.
The following example uses a try
-with-resources statement to automatically close an java.sql.Statement
object:
1 Public Static voidViewtable (Connection con)throwsSQLException {2 3String query = "Select Cof_name, sup_id, Price, SALES, total from coffees";4 5 Try(Statement stmt =con.createstatement ()) {6 7ResultSet rs =stmt.executequery (query);8 9 while(Rs.next ()) {TenString coffeename = rs.getstring ("Cof_name"); One intSupplierID = Rs.getint ("sup_id"); A floatPrice = Rs.getfloat ("Price"); - intSales = Rs.getint ("Sales"); - intTotal = Rs.getint ("Total"); theSystem.out.println (Coffeename + "," + SupplierID + "," + Price + -"," + Sales + "," +Total ); - } - +}Catch(SQLException e) { - jdbctutorialutilities.printsqlexception (e); + } A}
View Code
This resource used in this example java.sql.Statement
is part of JDBC 4.1 and subsequent versions of the API.
Note : A try
-with-resources statement can try
have and block like a normal catch
statement finally
. In the try
-with-resources statement, any catch
or all of the finally
blocks run after the declared resource is closed.
Suppressed anomalies
try
the code block associated with the-with-resources statement may throw an exception. When writeToFileZipFileContents这个例子中
attempting to close ZipFile
and BufferedWriter
object, the try
block may throw an exception, and the try
-with-resources statement may throw up to two exceptions. If the try
block throws an exception and the try
-with-resources statement throws one or more exceptions, the try
exception thrown from the-with-resources statement is suppressed, and the exception thrown by the block is the writeToFileZipFileContents
one thrown by the method. You can try块抛出的异常的
Throwable.getSuppressed
retrieve these suppressed exception information by calling the method .
Class that implements the Autocloseable or Closeable interface
See also the Javadoc of the AutoCloseable
Closeable
interface to see the set of classes that implement either of the two interfaces . Closeable
interface inherits the interface AutoCloseable
. The method of the interface Closeable
close
throws a IOException
type of exception and the method of the AutoCloseable
interface close
throws so that the subclass of the subclasses of the Exception 类型的异常。
AutoCloseable
interface can override the close
method of this Behavior to throw the specified exception, for example IOException
, or no exception.
This document is translated from the Oracle official documentation http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html, if there is an incorrect place , please correct me, thank you!
Java NIO try-with-resources [reprint]