The try-with-resources Statement
try-with-resources 聲明
The try
-with-resources statement is a try
statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try
-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
try-with-resources聲明是一個(gè)try聲明中定義了一個(gè)或多個(gè)資源实幕。資源是指程序結(jié)束使用它后必須被關(guān)閉的實(shí)體。try-with-resources聲明可以確保每一個(gè)資源都會(huì)在聲明結(jié)束部分被關(guān)閉堤器。任何實(shí)現(xiàn)了java.lang.AutoCloseable
昆庇,包括所有實(shí)現(xiàn)了java.io.Closeable
可以被當(dāng)做資源使用。
The following example reads the first line from a file. It uses an instance of BufferedReader
to read data from the file. BufferedReader
is a resource that must be closed after the program is finished with it:
下面的例子讀取了文件的第一行闸溃。它使用了一個(gè)BufferedReader
實(shí)例來(lái)讀取文件中的數(shù)據(jù)整吆。BufferedReader
是一個(gè)程序結(jié)束后必須被關(guān)閉的資源。
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 will be closed regardless of whether the try
statement completes normally or abruptly (as a result of the method BufferedReader.readLine
throwing an IOException
).
在這個(gè)例子中辉川,一個(gè)BufferedReader
作為資源聲明在了try-with-resources結(jié)構(gòu)中表蝙。聲明的動(dòng)作出現(xiàn)在try關(guān)鍵字之后的圓括號(hào)內(nèi)。在JavaSE7以及之后版本,BufferedReader
類實(shí)現(xiàn)了接口java.lang.AutoCloseable
择同,因?yàn)?code>BufferedReader實(shí)例聲明在了try-with-resources結(jié)構(gòu)中毛嫉,它一定會(huì)被關(guān)閉雌桑,不論try結(jié)構(gòu)的代碼完整執(zhí)行還是產(chǎn)生異常(BufferedReader.readLine
方法的結(jié)果是可能拋出IO異常的)汇跨。
Prior to Java SE 7, you can use a finally
block to ensure that a resource is closed regardless of whether the try
statement completes normally or abruptly. The following example uses a finally
block instead of a try
-with-resources statement:
JavaSE7之前的版本,您可以使用finally
代碼塊來(lái)確保資源可以被關(guān)閉函匕,不論try代碼塊是否報(bào)異常蚪黑。下面的例子使用了finally
代碼塊代替try-with-resources
結(jié)構(gòu)忌穿。
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 are thrown from both the try
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 block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.
但是蓬推,在這例子中澡腾,如果readLine
和close
兩個(gè)方法都拋出異常动分,那么方法readFirstLineFromFileWithFinallyBlock
就會(huì)拋出異常澜公,這個(gè)異常由finally
代碼塊中拋出;try
代碼塊中的拋出的異常被抑制了迹辐。相反地明吩,在例子readFirstLineFromFile
中殷费,如果異常try
代碼塊以及try-with-resources
結(jié)構(gòu)中都拋出異常详羡,那么readFirstLineFromFile
方法拋出的異常會(huì)由try
代碼塊拋出;由try-with-resources
結(jié)構(gòu)中拋出的異常會(huì)被抑制水泉。在JavaSE7以及之后版本中草则,你可以恢復(fù)被抑制的異常畔师,更多信息請(qǐng)查看文檔Suppressed Exceptions
You may 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 zipFileName
and creates a text file that contains the names of these files:
在try-with-resources
結(jié)構(gòu)中看锉,你可能會(huì)聲明一個(gè)或多個(gè)資源塔鳍。下面的例子檢索了打包在zip壓縮文件zipFileName
中的文件的名稱,并且創(chuàng)建了一個(gè)文本文件來(lái)保存這些文件名轮纫。
public static void writeToFileZipFileContents(String zipFileName,
String outputFileName)
throws java.io.IOException {
java.nio.charset.Charset charset =
java.nio.charset.StandardCharsets.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)
) {
// Enumerate 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 two declarations that are separated by a semicolon: ZipFile
and BufferedWriter
. When the block of code that directly follows it terminates, either normally or because of an exception, the close
methods of the BufferedWriter
and ZipFile
objects are automatically called in this order. Note that the close
methods of resources are called in the opposite order of their creation.
在這個(gè)例子中放前,try-with-resources
結(jié)構(gòu)包含了ZipFile
和 BufferedWriter
兩個(gè)資源的聲明凭语,它們由分號(hào)隔開似扔。無(wú)論是否產(chǎn)生異常炒辉,當(dāng)代碼塊執(zhí)行完畢時(shí)泉手,BufferedWriter
和 ZipFile
的close
方法都會(huì)被自定地執(zhí)行斩萌。請(qǐng)注意术裸,是先執(zhí)行BufferedWriter
的close
,后執(zhí)行ZipFile
的close
搀崭,這個(gè)順序與他們的創(chuàng)建順序是相反的瘤睹。
The following example uses a try
-with-resources statement to automatically close a java.sql.Statement
object:
下面的例子使用了try-with-resources
聲明自動(dòng)關(guān)閉了java.sql.Statement
對(duì)象轰传。
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.
例子中的java.sql.Statement
作為資源是JDBC4.1以及之后版本的一部分港庄。
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.
請(qǐng)注意:try-with-resources
聲明也可以像平常的try
結(jié)構(gòu)一樣使用catch
和finally
代碼塊鹏氧。在try-with-resources
結(jié)構(gòu)中佩谣,所有的catch
或finally
代碼塊會(huì)在資源被關(guān)閉后執(zhí)行茸俭。
Suppressed Exceptions
被抑制的異常
An exception can be thrown from the block of code associated with the try
-with-resources statement. In the example writeToFileZipFileContents
, an exception can be thrown from the try
block, and up to two exceptions can be thrown from the try
-with-resources statement when it tries to close the ZipFile
and BufferedWriter
objects. If an exception is thrown from the try
block and one or more exceptions are thrown from the try
-with-resources statement, then those exceptions thrown from the try
-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents
method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed
method from the exception thrown by the try
block.
在try-with-resources
聲明中调鬓,代碼塊中可以拋出異常。在writeToFileZipFileContents
的例子中冕臭,try
代碼塊可以爆出一個(gè)異常辜贵,嘗試關(guān)閉兩個(gè)資源時(shí)托慨,try-with-resources
聲明中最多可以拋出兩個(gè)異常。如果try
代碼塊拋出一個(gè)異常厚棵,try-with-resources
聲明中拋出一個(gè)或兩個(gè)異常婆硬,那么try-with-resources
聲明中拋出的異常會(huì)被抑制奸例,try
代碼塊中的異常會(huì)被方法writeToFileZipFileContents
拋出向楼。你可以通過(guò)調(diào)用try
代碼塊中拋出的異常對(duì)象的Throwable.getSuppressed
方法來(lái)恢復(fù)那些被抑制的異常湖蜕。
Classes That Implement the AutoCloseable or Closeable Interface
那些實(shí)現(xiàn)了AutoCloseable
或Closeable
接口的類
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 IOException
while the close
method of the AutoCloseable
interface throws exceptions of type Exception
. Consequently, subclasses of the AutoCloseable
interface can override this behavior of the close
method to throw specialized exceptions, such as IOException
, or no exception at all.
查看java文檔AutoCloseable
和 Closeable
獲取一個(gè)列表,這個(gè)列表中的類實(shí)現(xiàn)了這兩個(gè)接口中的其中一個(gè)炼杖。Closeable
接口繼承了AutoCloseable
接口。Closeable
接口中的close
方法拋出了IOException
的異常婆殿,然而AutoCloseable
接口中的close
方法拋出了Exception
類型的異常罩扇。因此喂饥,實(shí)現(xiàn)了AutoCloseable
接口的子類可以重寫這個(gè)close
方法來(lái)覆蓋這個(gè)行為员帮,可以改成拋出指定異常导饲,例如IOException
渣锦,或者根本不拋出異常。