Java7新语法 -try-with-resources

翻译 2015年11月20日 15:32:41

http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is as 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.

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:

使用try-with-resources, 可以自动关闭实现了AutoCloseable或者Closeable接口的资源。比如下面的函数,在try语句结束后,不论其包括的代码是正常执行完毕还是发生异常,都会自动调用BufferdReader的Close方法。

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).

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:

在出现try-with-resources之前可以使用finally子句来确保资源被关闭, 比如下面的方法。
但是两者有一个不同在于,readFirstLineFromFileWithFinallyBlock方法中,如果finally子句中抛出异常,将会抑制try代码块中抛出的异常。
相反,readFirstLineFromFile方法中,如果try-with-resources语句中打开资源的Close方法和try代码块中都抛出了异常,Close方法抛出的异常被抑制,try代码块中的异常会被抛出。
关于这一点,可以看最后的例子。

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 tryblock 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.

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语句中声明多个资源,这些资源将会以声明的顺序相反之顺序关闭, 比如下面的方法。

  public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {

    java.nio.charset.Charset charset = java.nio.charset.Charset.forName("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.

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:

  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.

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语句也能够有catch和finally子句。catch和finally子句将会在try-with-resources子句中打开的资源被关闭之后得到调用。

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语句中打开资源的Close方法和try代码块中都抛出了异常,Close 方法抛出的异常被抑制,try代码块中的异常会被抛出。
Java7之后,可以使用Throwable.getSuppressed方法获得被抑制的异常。

Classes That Implement the AutoCloseable or Closeable Interface

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 Closeableinterface 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 theclose method to throw specialized exceptions, such as IOException, or no exception at all.

示例

import java.io.Closeable;
import java.io.IOException;

public class DummyClosable implements Closeable {
    private final boolean throwInClose;
    private final String name;

    public DummyClosable(boolean throwInConstruction, boolean throwInClose, String name) throws IOException {
        this.throwInClose = throwInClose;
        this.name = name;
        if (throwInConstruction) {
            throw new IOException("throwing in construction");
        }
    }

    @Override
    public void close() throws IOException {
        if (throwInClose) {
            throw new IOException("throwing in close");
        }
        System.out.println(name + " is closing...");
    }

    public static void main(String[] args) {
        try (DummyClosable d1 = new DummyClosable(false, false, "a");
                DummyClosable d2 = new DummyClosable(true, false, "b");) {
            throw new IOException("in main1");
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        System.out.println("----end1----");

        try (DummyClosable d1 = new DummyClosable(false, false, "a");
                DummyClosable d2 = new DummyClosable(false, true, "b");) {
            throw new IOException("in main2");
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        System.out.println("----end2----");
    }
}

运行上面的例子,结果如下:
a is closing...
java.io.IOException: throwing in construction
	at learning.io.DummyClosable.<init>(DummyClosable.java:14)
	at learning.io.DummyClosable.main(DummyClosable.java:28)
----end1----
a is closing...
java.io.IOException: in main2
	at learning.io.DummyClosable.main(DummyClosable.java:37)
	Suppressed: java.io.IOException: throwing in close
		at learning.io.DummyClosable.close(DummyClosable.java:21)
		at learning.io.DummyClosable.main(DummyClosable.java:38)
----end2----



try-with-resources 语句

try-with-resources 语句是声明一个或多个资源的try语句,在程序执行完后资源一定会随之被关闭,try-with-resources语句确保每一个声明的资源都会在该语句执行完毕后被关...
  • zxc123e
  • zxc123e
  • 2014年03月14日 15:16
  • 1915

Java SE7新特性之try-with-resources语句

try-with-resources语句是一个声明一个或多个资源的 try 语句。一个资源作为一个对象,必须在程序结束之后随之关闭。 try-with-resources语句确保在语句的最后每个资源都...
  • jackiehff
  • jackiehff
  • 2014年01月02日 21:02
  • 33024

java try-with-resources 语句

java try-with-resources 语句
  • shangboerds
  • shangboerds
  • 2015年10月29日 16:51
  • 872

使用try-with-resources自动释放资源

Java 7中引入的使用try语句进行资源管理的新用法 类似.net中的using,不管有没有异常出现都会 对资源进行释放当然该类必须实现 java.lang.AutoCloseable接口 ...
  • aojiancc2
  • aojiancc2
  • 2013年12月12日 18:13
  • 696

Jdk1.7(及以上) 使用 try-with-resources 替代try-catch-finally

刚刚在看 Jedis's Wiki 的时候,发现里边的代码,用了一句 还没见过这样的语法,于是乎到官方找了一下解释  http://docs.oracle.com/javase/7/docs/tech...
  • lc0817
  • lc0817
  • 2016年12月30日 16:53
  • 351

Java7里try-with-resources分析

这个所谓的try-with-resources,是个语法糖。实际上就是自动调用资源的close()函数。和Python里的with语句差不多。 例如: static String readFirs...
  • hengyunabc
  • hengyunabc
  • 2014年01月18日 22:18
  • 30851

try-with-resources 语句,自动资源释放

关于try(){} http://www.oschina.net/question/12_10706
  • xuanfengling
  • xuanfengling
  • 2016年05月19日 15:53
  • 174

java se1.7 try-with-resources 使用

在进行java编程的过程中,出现文件流未关闭或者connection未关闭的情况,很难发现而且出现的问题也不知道是哪里的问题,无意中发现javase1.7开始出现try-with-resources,...
  • zhijiesmile
  • zhijiesmile
  • 2017年07月19日 16:12
  • 117

suppressedExceptions

addSuppressed()方法 开发人员对异常处理的try-catch-finally语句块都比较熟悉。如果在try语句块中抛出了异常,在控制权转移到调用栈上一层代码之前,finally语句块中...
  • gxftry1st
  • gxftry1st
  • 2017年03月23日 14:51
  • 407

Java 1.7新特性之(try-with-resources)

翻译自官方提供的使用说明。
  • fanxiaobin577328725
  • fanxiaobin577328725
  • 2016年11月07日 19:24
  • 1346
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java7新语法 -try-with-resources
举报原因:
原因补充:

(最多只允许输入30个字)