2013年12月21日 星期六

The try-with-resources Statement
許裕永 譯 (原文內容取自 Oracle 官網)

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 the new java.lang.AutoCloseable interface or the java.io.Closeable interface can be used as a resource. The classes java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement.
try-with-resources 敘述 - 這個 try-with-resources 敘述是一個 try 敘述, 它宣告了一個或多個 resources. resource 是一個必須在程式結束時會一起關閉的物件. try-with-resources 敘述確保每一個 resource 會在敘述結束使用它之後被關閉. 任何物件只要實作了新的 java.lang.AutoCloseable 或 java.io.Closeable 界面, 就可以被當作是 resource 使用. 新樣式的類別 java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statememt, 以及 ResultSet 都已經實作 AutoCloseable 界面, 而且已經可以被使用在 try-with-resources 敘述中.

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). Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the whether the try statement completes normally or abruptly.
在這個範例, 這個 resource 是一個 BufferredReader, 它宣告在 try-with-resources 敘述之中. 宣告敘述位於緊接在 try 關鍵字之後的圓括號之後. 類別 BufferedReader 在 Java SE7 及以後版本中, 已實作了 java.lang.AutoCloseable 界面. 因為這個 BufferedReaqder 的實體是宣告在 try-with-reasources 敘述中, 它將會一定會關閉, 無論 try 敘述是正常的或意外的結束 (就像結果是由方法 BufferedReader.readLine 丟出 IOException) . 在 Java SE7 之前, 你可以使抈 finally 區塊來確保 resorece 一定會關閉, 無論 try 敘述是正常的或意外的結束.

The following example uses a finally block instead of a try-with-resources statement:
下列範例使用 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 這兩個方法都有可能丟出 exceptions, 由方法 readfirstLineFromFileWithFinallyBlock 宣告了來自 finally 區塊的 exception; 而 try 區塊中的 exception 是受到抑制的. 相對比較, 以範例 readFirstLineFromFile而言, 假設 exception 被從同時擁有 try 及 try-with-resources 的方法中丟出, 那麼從 readFirstLineFromFile 方法中丟出的 exception 會是來自於 try 區塊; 在 try-with-resources 中的 exception 是受到抑制的. 在 Java SE 7 以及以後的版本, 你可以追踪受抑制的 exception; 參閱單元  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:
你可能宣告一個或多個 resources 在 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.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-resource 敘述包含了用冒號區隔的兩個宣告: ZipFile 及 BufferedWriter. 區塊中的程式碼無論是正常的或是由於產生 exception 而結束, BufferedWriter 及 ZipFile 物件的 close 方法會依特定順定自動被呼叫. 注意, close 方法的呼叫是依照物件被建立的相反順序.

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
下列範例使用了一個 try-with-resource 敘述來自動關閉一個 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.
這個範例中使用的  resource java.sql.Statement 是 JDBC 4.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 敘述可以有 catch 及 finally 區塊, 就像普通的 try 敍敘. 在 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-with-resources.
受抑制的 Exceptions
try-with-resources 敘述的區塊中的相關程式碼可能產生 exception. 在範例中 writeToFileZipFileContents 可能丟出來自於 try 區塊的 exception, 以及最多兩個來自於 try-with-resources 敘述的 exceptions, 當它嘗試關閉 ZipFile 和 BufferedWriter 物件時. 如果丟出來的 exception 是來自於 try 區塊以及一個或多個 exceptions 來自於 try-with-resources 敘述, 那麼那些來自於 try-with-resources 敘述的 exception 是受到抑制的, 而來自於 try 區塊的 exception 才是那個會被 writeToFileZipFileContents 方法丟出的 exception. 你可以呼叫 Throwable.getSupperssed 方法來取得這些來自於 try-with-sources 的被抑制的 excepions.


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.
實作 AutoCloseable 或 Closeable 界面的類別
查閱 Javadoc 關於 AutoCloseable 及 Closeable 界面的相關類別無論是否實作這些界面. Closeable 界面延伸自 AutoCloseable 界面. Closeable 界面中的 close 方法所 throws 的 exception 的型別是 IOException, 然而 AutoCloseable 界面的 close 方法所 throws 的 exception 的型別卻是 Exception. 所以, AutoCloseable 界面的下層類別可以用這種模式, 在 override close 這個方法時, throws 特定的 exception, 像是 IOException, 或完全沒有 exception.

沒有留言:

張貼留言