【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声明是一个try声明中定义了一个或多个资源。资源是指程序结束使用它后必须被关闭的实体。try-with-resources声明可以确保每一个资源都会在声明结束部分被关闭。任何实现了java.lang.AutoCloseable,包括所有实现了java.io.Closeable可以被当做资源使用。

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是一个程序结束后必须被关闭的资源。

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).
在这个例子中,一个BufferedReader作为资源声明在了try-with-resources结构中。声明的动作出现在try关键字之后的圆括号内。在JavaSE7以及之后版本,BufferedReader类实现了接口java.lang.AutoCloseable,因为BufferedReader实例声明在了try-with-resources结构中,它一定会被关闭,不论try结构的代码完整执行还是产生异常(BufferedReader.readLine方法的结果是可能抛出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代码块来确保资源可以被关闭,不论try代码块是否报异常。下面的例子使用了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.

但是,在这例子中,如果readLineclose两个方法都抛出异常,那么方法readFirstLineFromFileWithFinallyBlock就会抛出异常,这个异常由finally代码块中抛出;try代码块中的抛出的异常被抑制了。相反地,在例子readFirstLineFromFile中,如果异常try代码块以及try-with-resources结构中都抛出异常,那么readFirstLineFromFile方法抛出的异常会由try代码块抛出;由try-with-resources结构中抛出的异常会被抑制。在JavaSE7以及之后版本中,你可以恢复被抑制的异常,更多信息请查看文档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结构中,你可能会声明一个或多个资源。下面的例子检索了打包在zip压缩文件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());
        }
    }
}

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-resources结构包含了ZipFileBufferedWriter两个资源的声明,它们由分号隔开。无论是否产生异常,当代码块执行完毕时,BufferedWriterZipFileclose方法都会被自定地执行。请注意,是先执行BufferedWriterclose,后执行ZipFileclose,这个顺序与他们的创建顺序是相反的

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
下面的例子使用了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);
    }
}

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.
请注意try-with-resources声明也可以像平常的try结构一样使用catchfinally代码块。在try-with-resources结构中,所有的catchfinally代码块会在资源被关闭后执行。

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代码块可以爆出一个异常,尝试关闭两个资源时,try-with-resources声明中最多可以抛出两个异常。如果try代码块抛出一个异常,try-with-resources声明中抛出一个或两个异常,那么try-with-resources声明中抛出的异常会被抑制,try代码块中的异常会被方法writeToFileZipFileContents抛出。你可以通过调用try代码块中抛出的异常对象的Throwable.getSuppressed方法来恢复那些被抑制的异常。

Classes That Implement the AutoCloseable or Closeable Interface

那些实现了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获取一个列表,这个列表中的类实现了这两个接口中的其中一个。Closeable接口继承了AutoCloseable接口。Closeable接口中的close方法抛出了IOException的异常,然而AutoCloseable接口中的close方法抛出了Exception类型的异常。因此,实现了AutoCloseable接口的子类可以重写这个close方法来覆盖这个行为,可以改成抛出指定异常,例如IOException,或者根本不抛出异常。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,816评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,729评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,300评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,780评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,890评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,084评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,151评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,912评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,355评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,666评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,809评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,504评论 4 334
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,150评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,882评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,121评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,628评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,724评论 2 351

推荐阅读更多精彩内容

  • 原文链接: https://docs.oracle.com/javase/tutorial/essential/e...
    ColdWave阅读 828评论 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,312评论 0 10
  • The Java libraries include many resources that must be cl...
    MrDcheng阅读 596评论 0 0
  • 忍不住还是发火了,还有9天要中考了,躲着听手机音乐。 这两天没有跑什么盘,明天还是投资把5.8开起来。...
    徐丽红阅读 170评论 0 0
  • 虽然还没回到老家,但是心已经飞到那里去了,这几天不管是白天,还是夜里总会幻想着在家的各种情景。 首先想到的是我们三...
    小海堂阅读 58评论 0 0