【Using English】54 The try-with-resources Statement

original

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聲明是一個try聲明中定義了一個或多個資源。資源是指程序結束使用它后必須被關閉的實體。try-with-resources聲明可以確保每一個資源都會在聲明結束部分被關閉。任何實現了java.lang.AutoCloseable,包括所有實現了java.io.Closeable可以被當做資源使用。

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是一個程序結束后必須被關閉的資源。

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作為資源聲明在了try-with-resources結構中。聲明的動作出現在try關鍵字之后的圓括號內。在JavaSE7以及之后版本,BufferedReader類實現了接口java.lang.AutoCloseable,因為BufferedReader實例聲明在了try-with-resources結構中,它一定會被關閉,不論try結構的代碼完整執行還是產生異常(BufferedReader.readLine方法的結果是可能拋出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代碼塊來確保資源可以被關閉,不論try代碼塊是否報異常。下面的例子使用了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.

但是,在這例子中,如果readLineclose兩個方法都拋出異常,那么方法readFirstLineFromFileWithFinallyBlock就會拋出異常,這個異常由finally代碼塊中拋出;try代碼塊中的拋出的異常被抑制了。相反地,在例子readFirstLineFromFile中,如果異常try代碼塊以及try-with-resources結構中都拋出異常,那么readFirstLineFromFile方法拋出的異常會由try代碼塊拋出;由try-with-resources結構中拋出的異常會被抑制。在JavaSE7以及之后版本中,你可以恢復被抑制的異常,更多信息請查看文檔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結構中,你可能會聲明一個或多個資源。下面的例子檢索了打包在zip壓縮文件zipFileName中的文件的名稱,并且創建了一個文本文件來保存這些文件名。

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.

在這個例子中,try-with-resources結構包含了ZipFileBufferedWriter兩個資源的聲明,它們由分號隔開。無論是否產生異常,當代碼塊執行完畢時,BufferedWriterZipFileclose方法都會被自定地執行。請注意,是先執行BufferedWriterclose,后執行ZipFileclose,這個順序與他們的創建順序是相反的

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
下面的例子使用了try-with-resources聲明自動關閉了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以及之后版本的一部分。

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結構一樣使用catchfinally代碼塊。在try-with-resources結構中,所有的catchfinally代碼塊會在資源被關閉后執行。

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代碼塊可以爆出一個異常,嘗試關閉兩個資源時,try-with-resources聲明中最多可以拋出兩個異常。如果try代碼塊拋出一個異常,try-with-resources聲明中拋出一個或兩個異常,那么try-with-resources聲明中拋出的異常會被抑制,try代碼塊中的異常會被方法writeToFileZipFileContents拋出。你可以通過調用try代碼塊中拋出的異常對象的Throwable.getSuppressed方法來恢復那些被抑制的異常。

Classes That Implement the AutoCloseable or Closeable Interface

那些實現了AutoCloseableCloseable接口的類

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文檔AutoCloseableCloseable獲取一個列表,這個列表中的類實現了這兩個接口中的其中一個。Closeable接口繼承了AutoCloseable接口。Closeable接口中的close方法拋出了IOException的異常,然而AutoCloseable接口中的close方法拋出了Exception類型的異常。因此,實現了AutoCloseable接口的子類可以重寫這個close方法來覆蓋這個行為,可以改成拋出指定異常,例如IOException,或者根本不拋出異常。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 原文鏈接: https://docs.oracle.com/javase/tutorial/essential/e...
    ColdWave閱讀 843評論 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,449評論 0 10
  • The Java libraries include many resources that must be cl...
    MrDcheng閱讀 624評論 0 0
  • 忍不住還是發火了,還有9天要中考了,躲著聽手機音樂。 這兩天沒有跑什么盤,明天還是投資把5.8開起來。...
    徐麗紅閱讀 176評論 0 0
  • 雖然還沒回到老家,但是心已經飛到那里去了,這幾天不管是白天,還是夜里總會幻想著在家的各種情景。 首先想到的是我們三...
    小海堂閱讀 61評論 0 0