您的位置:首页 > 数据库 > Oracle

Oracle官方文档 —— The try-with-resources Statement

2018-02-11 09:52 260 查看

The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is as 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语句是一个声明一个或多个resources的try语句。Resource是指在程序使用结束后必须被关闭的对象。try-with-resources语句保证每个resource都会在语句结束时被关闭。任何实现了
java.lang.AutoCloseable
java.io.Closeable
接口的对象都可以视作resource。

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:

下面这个程序的例子会读取文件的第一行,它使用了
BufferedReader
的实例来从文件中读取数据。
BufferedReader
是一个程序使用完以后必须关闭的resource。

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).

在这个例子中,
BufferedReader
作为resource在try-with-resources语句中被声明,声明语句放在紧跟在try这个关键字后的小括号中。BufferedReader这个类,在Java SE 7以及更后面的版本中实现了
java.lang.AutoCloseable
这个接口。如果BufferedReader实例在一个try-with-resource的语句中被声明,那么不管try语句是否成功执行这个resource都会被关闭(执行
BufferedReader.readLine
这个方法的结果是抛出IOExcepetion异常)。

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:

在Java SE 7之前的版本里,你可以使用finally块来确保resource在任何情况下都能被关闭,下面的这个例子就是使用finally块代替
try-with-resources
语句:

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都抛出错误,这时方法readFirstLineFromFileWithFinallyBlock 会抛出finally块中抛出的异常;而来自try语句块中的异常会被抑制。相比之下,在例子readFirstLineFromFile中,如果同时从try语句块和try-with-resources语句中抛出错误,那么这个方法实际会抛出try块中的异常;来自try-with-resources块中的异常会被抑制。在Java SE 7以及之后的版本中,你可以得到被抑制的异常;在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语句中声明多个resouces。下面的这个例子会从打包的zip文件zipFileName中获得这些文件的文件名,同时创建一个文本文件来储存这些文件名:

public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
throws java.io.IOException {

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)
) {

// 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, <
4000
span class="hljs-number">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.

在这个例子中,try-with-resources语句包含了两个用分号隔开的声明语句:
ZipFile
BufferedWriter
。当紧跟着这个语句的代码块结束时,不管是正常结束还是因为发生异常,BufferedWriter和ZipFile的close方法都会被自动地按顺序调用。注意这些resources的close方法的调用顺序和它们的创建语句顺序相反。

The following example uses a try-with-resources statement to automatically close a
java.sql.Statement
object:

下面的这个例子使用try-with-resouces语句自动关闭一个
java.sql.Statement
对象:

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及之后版本的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.

注意:一个
try-with-resources
语句中也可以像单个try语句一样拥有catch和finally语句块。在一个try-with-resources语句中,任何catch或者finally语句块将在resources打开的资源被关闭后执行。

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后的语句块中可能抛出异常,而且当试图关闭
ZipFile
BufferedWriter
对象时,try-with-resouces语句中可能抛出多达两个异常。如果有一个来自try语句块的异常和多个来自try-with-resources语句的异常,那么来自try-with-resources语句中的异常抛出会被抑制,块中的那个异常会被这个方法抛出。你可以通过调用
Throwable.getSuppressed
方法来获得那些被try块抑制的异常。

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 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.

查看Javadoc可以找到实现了
AutoCloseable
Closeable
之一的接口的类列表。Closeable接口继承自AutoCloseable接口。Closeable接口中的close方法抛出的是IOException类型的异常,而AutoCloseable接口中抛出的是Exception类型的异常。因此,实现AutoCloseable接口的类可以重写这个close方法让它更加具体,例如IOException或者不抛出异常。

PS:英文水平有限,只能做到把文章的意思用中文复述了一遍。也没有加一些自己的理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 7 oracle文档