【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聲明是一個(gè)try聲明中定義了一個(gè)或多個(gè)資源实幕。資源是指程序結(jié)束使用它后必須被關(guān)閉的實(shí)體。try-with-resources聲明可以確保每一個(gè)資源都會(huì)在聲明結(jié)束部分被關(guān)閉堤器。任何實(shí)現(xiàn)了java.lang.AutoCloseable昆庇,包括所有實(shí)現(xiàn)了java.io.Closeable可以被當(dāng)做資源使用。

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:
下面的例子讀取了文件的第一行闸溃。它使用了一個(gè)BufferedReader實(shí)例來(lái)讀取文件中的數(shù)據(jù)整吆。BufferedReader是一個(gè)程序結(jié)束后必須被關(guān)閉的資源。

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).
在這個(gè)例子中辉川,一個(gè)BufferedReader作為資源聲明在了try-with-resources結(jié)構(gòu)中表蝙。聲明的動(dòng)作出現(xiàn)在try關(guān)鍵字之后的圓括號(hào)內(nèi)。在JavaSE7以及之后版本,BufferedReader類實(shí)現(xiàn)了接口java.lang.AutoCloseable择同,因?yàn)?code>BufferedReader實(shí)例聲明在了try-with-resources結(jié)構(gòu)中毛嫉,它一定會(huì)被關(guān)閉雌桑,不論try結(jié)構(gòu)的代碼完整執(zhí)行還是產(chǎn)生異常(BufferedReader.readLine方法的結(jié)果是可能拋出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代碼塊來(lái)確保資源可以被關(guān)閉函匕,不論try代碼塊是否報(bào)異常蚪黑。下面的例子使用了finally代碼塊代替try-with-resources結(jié)構(gòu)忌穿。

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兩個(gè)方法都拋出異常动分,那么方法readFirstLineFromFileWithFinallyBlock就會(huì)拋出異常澜公,這個(gè)異常由finally代碼塊中拋出;try代碼塊中的拋出的異常被抑制了迹辐。相反地明吩,在例子readFirstLineFromFile中殷费,如果異常try代碼塊以及try-with-resources結(jié)構(gòu)中都拋出異常详羡,那么readFirstLineFromFile方法拋出的異常會(huì)由try代碼塊拋出;由try-with-resources結(jié)構(gòu)中拋出的異常會(huì)被抑制水泉。在JavaSE7以及之后版本中草则,你可以恢復(fù)被抑制的異常畔师,更多信息請(qǐng)查看文檔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結(jié)構(gòu)中看锉,你可能會(huì)聲明一個(gè)或多個(gè)資源塔鳍。下面的例子檢索了打包在zip壓縮文件zipFileName中的文件的名稱,并且創(chuàng)建了一個(gè)文本文件來(lái)保存這些文件名轮纫。

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.

在這個(gè)例子中放前,try-with-resources結(jié)構(gòu)包含了ZipFileBufferedWriter兩個(gè)資源的聲明凭语,它們由分號(hào)隔開似扔。無(wú)論是否產(chǎn)生異常炒辉,當(dāng)代碼塊執(zhí)行完畢時(shí)泉手,BufferedWriterZipFileclose方法都會(huì)被自定地執(zhí)行斩萌。請(qǐng)注意术裸,是先執(zhí)行BufferedWriterclose,后執(zhí)行ZipFileclose搀崭,這個(gè)順序與他們的創(chuàng)建順序是相反的瘤睹。

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
下面的例子使用了try-with-resources聲明自動(dòng)關(guān)閉了java.sql.Statement對(duì)象轰传。

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.
請(qǐng)注意try-with-resources聲明也可以像平常的try結(jié)構(gòu)一樣使用catchfinally代碼塊鹏氧。在try-with-resources結(jié)構(gòu)中佩谣,所有的catchfinally代碼塊會(huì)在資源被關(guān)閉后執(zhí)行茸俭。

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代碼塊可以爆出一個(gè)異常辜贵,嘗試關(guān)閉兩個(gè)資源時(shí)托慨,try-with-resources聲明中最多可以拋出兩個(gè)異常。如果try代碼塊拋出一個(gè)異常厚棵,try-with-resources聲明中拋出一個(gè)或兩個(gè)異常婆硬,那么try-with-resources聲明中拋出的異常會(huì)被抑制奸例,try代碼塊中的異常會(huì)被方法writeToFileZipFileContents拋出向楼。你可以通過(guò)調(diào)用try代碼塊中拋出的異常對(duì)象的Throwable.getSuppressed方法來(lái)恢復(fù)那些被抑制的異常湖蜕。

Classes That Implement the AutoCloseable or Closeable Interface

那些實(shí)現(xiàn)了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獲取一個(gè)列表,這個(gè)列表中的類實(shí)現(xiàn)了這兩個(gè)接口中的其中一個(gè)炼杖。Closeable接口繼承了AutoCloseable接口。Closeable接口中的close方法拋出了IOException的異常婆殿,然而AutoCloseable接口中的close方法拋出了Exception類型的異常罩扇。因此喂饥,實(shí)現(xiàn)了AutoCloseable接口的子類可以重寫這個(gè)close方法來(lái)覆蓋這個(gè)行為员帮,可以改成拋出指定異常导饲,例如IOException渣锦,或者根本不拋出異常。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末型檀,一起剝皮案震驚了整個(gè)濱河市胀溺,隨后出現(xiàn)的幾起案子仓坞,更是在濱河造成了極大的恐慌,老刑警劉巖无埃,帶你破解...
    沈念sama閱讀 212,718評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倍啥,死亡現(xiàn)場(chǎng)離奇詭異虽缕,居然都是意外死亡蒲稳,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,683評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)祥国,“玉大人,你說(shuō)我怎么就攤上這事啊犬【踔粒” “怎么了睡腿?”我有些...
    開封第一講書人閱讀 158,207評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)应闯。 經(jīng)常有香客問(wèn)我孽锥,道長(zhǎng)细层,這世上最難降的妖魔是什么疫赎? 我笑而不...
    開封第一講書人閱讀 56,755評(píng)論 1 284
  • 正文 為了忘掉前任捧搞,我火速辦了婚禮狮荔,結(jié)果婚禮上殖氏,老公的妹妹穿的比我還像新娘雅采。我一直安慰自己慨亲,他們只是感情好刑棵,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,862評(píng)論 6 386
  • 文/花漫 我一把揭開白布蛉签。 她就那樣靜靜地躺著正蛙,像睡著了一般乒验。 火紅的嫁衣襯著肌膚如雪锻全。 梳的紋絲不亂的頭發(fā)上录煤,一...
    開封第一講書人閱讀 50,050評(píng)論 1 291
  • 那天妈踊,我揣著相機(jī)與錄音,去河邊找鬼歪泳。 笑死呐伞,一個(gè)胖子當(dāng)著我的面吹牛慎式,可吹牛的內(nèi)容都是我干的趟径。 我是一名探鬼主播蜗巧,決...
    沈念sama閱讀 39,136評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼惧蛹,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼香嗓!你這毒婦竟也來(lái)了靠娱?” 一聲冷哼從身側(cè)響起掠兄,我...
    開封第一講書人閱讀 37,882評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤迅诬,失蹤者是張志新(化名)和其女友劉穎侈贷,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體俏蛮,經(jīng)...
    沈念sama閱讀 44,330評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡搏屑,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,651評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了粉楚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辣恋。...
    茶點(diǎn)故事閱讀 38,789評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖模软,靈堂內(nèi)的尸體忽然破棺而出伟骨,到底是詐尸還是另有隱情,我是刑警寧澤撵摆,帶...
    沈念sama閱讀 34,477評(píng)論 4 333
  • 正文 年R本政府宣布底靠,位于F島的核電站,受9級(jí)特大地震影響特铝,放射性物質(zhì)發(fā)生泄漏暑中。R本人自食惡果不足惜壹瘟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,135評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧线欲,春花似錦、人聲如沸趴泌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,864評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)榄审。三九已至浪感,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間峻堰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,099評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工贺归, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人丹莲。 一個(gè)月前我還...
    沈念sama閱讀 46,598評(píng)論 2 362
  • 正文 我出身青樓洲赵,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親苛谷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,697評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容

  • 原文鏈接: https://docs.oracle.com/javase/tutorial/essential/e...
    ColdWave閱讀 828評(píng)論 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,312評(píng)論 0 10
  • The Java libraries include many resources that must be cl...
    MrDcheng閱讀 596評(píng)論 0 0
  • 忍不住還是發(fā)火了,還有9天要中考了,躲著聽手機(jī)音樂。 這兩天沒有跑什么盤迅涮,明天還是投資把5.8開起來(lái)据悔。...
    徐麗紅閱讀 168評(píng)論 0 0
  • 雖然還沒回到老家菠隆,但是心已經(jīng)飛到那里去了,這幾天不管是白天清女,還是夜里總會(huì)幻想著在家的各種情景。 首先想到的是我們?nèi)?..
    小海堂閱讀 58評(píng)論 0 0