java 7開始,提供了一種新的語法try-with-resources用于在資源使用完畢后自動關閉資源,和python中的with語句類似。“資源”指的是實現了java.lang.AutoCloseable的任意對象,因為java.io.Closeable是AutoCloseable的子接口,所以實現了Closeable的對象也可以用于該語法。
從文件中讀取第一行,無論try{}中的代碼塊是正常結束還是拋出異常(BufferdReader .readLine throw IOException),BufferdReader都會在使用完后會被自動關閉
static String readFirstLineFromFile(String path) throws IOException {    try (BufferedReader br =                   new BufferedReader(new FileReader(path))) {        return br.readLine();    }}Java 7之前,可以使用finally來實現類似的效果
static String readFirstLineFromFileWithFinallyBlock(String path)                                                     throws IOException {    BufferedReader br = new BufferedReader(new FileReader(path));    try {        return br.readLine();    } finally {        if (br != null) br.close();    }}但是finally方式和try-with-resources方式還是有所區別。finally方式中,如果readLine()和close()都同時拋出異常,try{}代碼塊中readLine()拋出的異常被捕獲,抑制拋出,而finally{}代碼塊中的close()拋出的異常被向上層調用拋出。try-with-resources對異常抑制的處理和finally相反,如果異常同時在try{}代碼塊和try-with-resources語句中拋出,最后try{}代碼塊中的異常將被拋出,try-with-resources語句中的異常會被抑制,如果需要獲得被抑制的異常,可以通過對拋出的異常調用Throwable.getSupPRessed()提取。
從zip文件中讀取其中的文件名,然后寫入一個文本文件中,通過分號分隔,try-with-resources語句中可以聲明多個資源
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語句中聲明的正好相反,上面的例子中,BufferedWriter先關閉,然后ZipFile才關閉。
利用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可以像傳統的try語句一樣,擁有配套的catch和finally語句塊,需要注意的是任何catch和finally語句塊都在聲明的資源被關閉之后才被運行。