Java7新语法 -try-with-resources

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

The try-with-resources Statement

Thetry-with-resources statement is atrystatement that declares one or more resources. Aresourceis as an object that must be closed after the program is finished with it. Thetry-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implementsjava.lang.AutoCloseable, which includes all objects which implementjava.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance ofBufferedReaderto read data from the file.BufferedReaderis 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 thetry-with-resources statement is aBufferedReader. The declaration statement appears within parentheses immediately after thetrykeyword. The classBufferedReader, in Java SE 7 and later, implements the interfacejava.lang.AutoCloseable. Because theBufferedReaderinstance is declared in atry-with-resource statement, it will be closed regardless of whether thetrystatement completes normally or abruptly (as a result of the methodBufferedReader.readLinethrowing anIOException).

Prior to Java SE 7, you can use afinallyblock to ensure that a resource is closed regardless of whether thetrystatement completes normally or abruptly. The following example uses afinallyblock instead of atry-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 methodsreadLineandcloseboth throw exceptions, then the methodreadFirstLineFromFileWithFinallyBlockthrows the exception thrown from thefinallyblock; the exception thrown from thetryblock is suppressed. In contrast, in the examplereadFirstLineFromFile, if exceptions are thrown from both thetryblock and thetry-with-resources statement, then the methodreadFirstLineFromFilethrows the exception thrown from thetryblock; the exception thrown from thetry-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the sectionSuppressed Exceptionsfor more information.

You may declare one or more resources in atry-with-resources statement. The following example retrieves the names of the files packaged in the zip filezipFileNameand 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, thetry-with-resources statement contains two declarations that are separated by a semicolon:ZipFileandBufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, theclosemethods of theBufferedWriterandZipFileobjects are automatically called in this order. Note that theclosemethods of resources are called in theoppositeorder of their creation.

The following example uses atry-with-resources statement to automatically close ajava.sql.Statementobject:

  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 resourcejava.sql.Statementused in this example is part of the JDBC 4.1 and later API.

Note: Atry-with-resources statement can havecatchandfinallyblocks just like an ordinarytrystatement. In atry-with-resources statement, anycatchorfinallyblock 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 thetry-with-resources statement. In the examplewriteToFileZipFileContents, an exception can be thrown from thetryblock, and up to two exceptions can be thrown from thetry-with-resources statement when it tries to close theZipFileandBufferedWriterobjects. If an exception is thrown from thetryblock and one or more exceptions are thrown from thetry-with-resources statement, then those exceptions thrown from thetry-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by thewriteToFileZipFileContentsmethod. You can retrieve these suppressed exceptions by calling theThrowable.getSuppressedmethod from the exception thrown by thetryblock.

注意:前面提到,如果try-with-resources语句中打开资源的Close方法和try代码块中都抛出了异常,Close 方法抛出的异常被抑制,try代码块中的异常会被抛出。
Java7之后,可以使用Throwable.getSuppressed方法获得被抑制的异常。

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of theAutoCloseableandCloseableinterfaces for a list of classes that implement either of these interfaces. TheCloseableinterface extends theAutoCloseableinterface. Theclosemethod of theCloseableinterface throws exceptions of typeIOExceptionwhile theclosemethod of theAutoCloseableinterface throws exceptions of typeException. Consequently, subclasses of theAutoCloseableinterface can override this behavior of theclosemethod to throw specialized exceptions, such asIOException, 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----



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值