Java編程——try-with-resources


try在開發中經常用到,我們熟悉的用法是:
try  Block
     [ { CatchClause } ]
     [ finally Block ]

在Java SE 7以後,我們可以使用try-with-resources :

try [ ( Resources ) ]
         Block
         [ { CatchClause } ]
         [ finally Block ]

看下面的兩個等價的例子:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}
try-with-resources ,很容易理解是聲明瞭一個或多個資源的try語句塊,這個資源對象在程序執行完之後必須關閉。並且確保在try語句結束時每個資源都關閉。任何一個可以作爲資源的對象必須是實現了java.lang.AutoCloseable接口的類的對象,並重寫其close方法。catch和finally字句在資源聲明結束後才執行。

下面的例子檢索壓縮文件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());
        }
    }
}

下面的例子使用 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);
    }
}

try-with-resources的優點:

1.便利性。只要資源類實現了AutoCloseable或Closeable程序在執行完try塊後會自動close所使用的資源無論br.readLine()是否拋出。異常實現資源的自動回收處理,大大提高了代碼的便利性,

2.更完全。在出現資源泄漏的程序中,很多情況是開發人員沒有或者開發人員沒有正確的關閉資源所導致的。JDK1.7之後採用try-with-resources的方式,則可以將資源關閉這種與業務實現沒有很大直接關係的工作交給JVM完成。省去了部分開發中可能出現的代碼風險。

3.高效率。try-with-resources語法更加高效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章