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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Armour__r/article/details/79308524

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.AutoCloseablejava.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, 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语句包含了两个用分号隔开的声明语句:ZipFileBufferedWriter。当紧跟着这个语句的代码块结束时,不管是正常结束还是因为发生异常,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后的语句块中可能抛出异常,而且当试图关闭ZipFileBufferedWriter对象时,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可以找到实现了AutoCloseableCloseable之一的接口的类列表。Closeable接口继承自AutoCloseable接口。Closeable接口中的close方法抛出的是IOException类型的异常,而AutoCloseable接口中抛出的是Exception类型的异常。因此,实现AutoCloseable接口的类可以重写这个close方法让它更加具体,例如IOException或者不抛出异常。

PS:英文水平有限,只能做到把文章的意思用中文复述了一遍。也没有加一些自己的理解。

猜你喜欢

转载自blog.csdn.net/Armour__r/article/details/79308524