1. 程式人生 > >java7新特性之Try-with-resources statement

java7新特性之Try-with-resources statement

try-with-resources 語句是一個聲明瞭1到多個資源的try語句。資源是指這個try執行完成後必需close掉的物件,比如connection, resultset等。

try-with-resources 語句會確保在try語句結束時關閉所有資源。實現了java.lang.AutoCloseablejava.io.Closeable的物件都可以做為資源。

下面是一個例子,它會從一個檔案中讀出首行文字,這裡使用了BufferedReader 的例項來讀取資料,BufferedReader是一個資源,它應該在程式完成時被關閉。

 
  1. static String readFirstLineFromFile(String path) throws IOException {

  2. try (BufferedReader br = new BufferedReader(new FileReader(path))) {

  3. return br.readLine();

  4. }

  5. }

在這個例子裡面,資源是一個BufferedReader, 宣告語句是在try後面的括號內。在java7或更晚的版本中,BufferedReader實現了java.lang.AutoCloseable介面。由於BufferedReader被定義在try-with-resource 語句中,因此不管try程式碼塊是正常完成或是出現異常,這個BufferedReader

 的例項都將被關閉。

在java7之前的版本中,你可以使用finally 程式碼塊來確保資源被關閉(不管try正常完成還是出現異常)。下面是使用finally的例子:

 
  1. static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {

  2. BufferedReader br = new BufferedReader(new FileReader(path));

  3. try {

  4. return br.readLine();

  5. } finally {

  6. if (br != null) br.close();

  7. }

  8. }

 

然而,在這裡例子裡面,如果readLine方法和close方法都丟擲了異常,readFirstLineFromFileWithFinallyBlock 方法只能丟擲finally程式碼塊裡面的異常,也就是close方法出現的異常,try程式碼塊裡面的異常被禁止;相反,在readFirstLineFromFile這個例子中,如果try 程式碼塊和try-with-resources 語句都出現異常,readFirstLineFromFile 方法將出丟擲來自try程式碼塊的異常,從try-with-resources丟擲的異常被禁止。在java7或更晚的版本中,我們可以獲取到這些被禁止的異常。

你可以宣告1到多個資源,看下面的例子

 
  1. public static void writeToFileZipFileContents(String zipFileName, String outputFileName)

  2. throws java.io.IOException {

  3.  
  4. java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");

  5. java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

  6.  
  7. // Open zip file and create output file with try-with-resources statement

  8.  
  9. try (

  10. java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);

  11. java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)

  12. ) {

  13.  
  14. // Enumerate each entry

  15.  
  16. for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

  17.  
  18. // Get the entry name and write it to the output file

  19.  
  20. String newLine = System.getProperty("line.separator");

  21. String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;

  22. writer.write(zipEntryName, 0, zipEntryName.length());

  23. }

  24. }

  25. }


 

在這個例子中,有兩個資源,資源之間用分號隔開。資源被關閉的順序與它們被建立的順序相反,也就是說writer 先被關閉,接著是zf。

 下面我們使用try-with-resources 語句自動關閉一個java.sql.Statement 物件:

 
  1. public static void viewTable(Connection con) throws SQLException {

  2.  
  3. String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

  4.  
  5. try (Statement stmt = con.createStatement()) {

  6.  
  7. ResultSet rs = stmt.executeQuery(query);

  8.  
  9. while (rs.next()) {

  10. String coffeeName = rs.getString("COF_NAME");

  11. int supplierID = rs.getInt("SUP_ID");

  12. float price = rs.getFloat("PRICE");

  13. int sales = rs.getInt("SALES");

  14. int total = rs.getInt("TOTAL");

  15. System.out.println(coffeeName + ", " + supplierID + ", " + price +

  16. ", " + sales + ", " + total);

  17. }

  18.  
  19. } catch (SQLException e) {

  20. JDBCTutorialUtilities.printSQLException(e);

  21. }

  22. }


這裡的java.sql.Statement 是JDBC4.1或更晚的API的一部分。

注意:try-with-resources 也可以有catch和finally語句塊,就像使用一個普通的try語句一樣。在try-with-resources 語句中,catch或者finally將在資源被關閉後執行。

from:https://blog.csdn.net/fireofjava/article/details/7220754