Java7新语法 -try-with-resources

简介: http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html The try-with-resources Statement The try-with-resources s...

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.

示例

[java]  view plain  copy
 
  1. import java.io.Closeable;  
  2. import java.io.IOException;  
  3.   
  4. public class DummyClosable implements Closeable {  
  5.     private final boolean throwInClose;  
  6.     private final String name;  
  7.   
  8.     public DummyClosable(boolean throwInConstruction, boolean throwInClose, String name) throws IOException {  
  9.         this.throwInClose = throwInClose;  
  10.         this.name = name;  
  11.         if (throwInConstruction) {  
  12.             throw new IOException("throwing in construction");  
  13.         }  
  14.     }  
  15.   
  16.     @Override  
  17.     public void close() throws IOException {  
  18.         if (throwInClose) {  
  19.             throw new IOException("throwing in close");  
  20.         }  
  21.         System.out.println(name + " is closing...");  
  22.     }  
  23.   
  24.     public static void main(String[] args) {  
  25.         try (DummyClosable d1 = new DummyClosable(false, false, "a");  
  26.                 DummyClosable d2 = new DummyClosable(true, false, "b");) {  
  27.             throw new IOException("in main1");  
  28.         } catch (Exception ex) {  
  29.             ex.printStackTrace(System.out);  
  30.         }  
  31.   
  32.         System.out.println("----end1----");  
  33.   
  34.         try (DummyClosable d1 = new DummyClosable(false, false, "a");  
  35.                 DummyClosable d2 = new DummyClosable(false, true, "b");) {  
  36.             throw new IOException("in main2");  
  37.         } catch (Exception ex) {  
  38.             ex.printStackTrace(System.out);  
  39.         }  
  40.   
  41.         System.out.println("----end2----");  
  42.     }  
  43. }  

运行上面的例子,结果如下:
[plain]  view plain  copy
 
  1. a is closing...  
  2. java.io.IOException: throwing in construction  
  3.     at learning.io.DummyClosable.<init>(DummyClosable.java:14)  
  4.     at learning.io.DummyClosable.main(DummyClosable.java:28)  
  5. ----end1----  
  6. a is closing...  
  7. java.io.IOException: in main2  
  8.     at learning.io.DummyClosable.main(DummyClosable.java:37)  
  9.     Suppressed: java.io.IOException: throwing in close  
  10.         at learning.io.DummyClosable.close(DummyClosable.java:21)  
  11.         at learning.io.DummyClosable.main(DummyClosable.java:38)  
  12. ----end2----  

 

http://blog.csdn.net/fw0124/article/details/49946975

 

相关文章
|
6月前
|
存储 Java 容器
Java基本语法详解
本文深入讲解了Java编程的基础语法,涵盖数据类型、运算符、控制结构及数组等核心内容,帮助初学者构建坚实的编程基础。
|
5月前
|
存储 SQL NoSQL
Redis-常用语法以及java互联实践案例
本文详细介绍了Redis的数据结构、常用命令及其Java客户端的使用,涵盖String、Hash、List、Set、SortedSet等数据类型及操作,同时提供了Jedis和Spring Boot Data Redis的实战示例,帮助开发者快速掌握Redis在实际项目中的应用。
356 1
Redis-常用语法以及java互联实践案例
|
5月前
|
Java
Java基础语法与面向对象
重载(Overload)指同一类中方法名相同、参数列表不同,与返回值无关;重写(Override)指子类重新实现父类方法,方法名和参数列表必须相同,返回类型兼容。重载发生在同类,重写发生在继承关系中。
182 1
|
7月前
|
Java 数据库连接 数据库
Java 相关知识点总结含基础语法进阶技巧及面试重点知识
本文全面总结了Java核心知识点,涵盖基础语法、面向对象、集合框架、并发编程、网络编程及主流框架如Spring生态、MyBatis等,结合JVM原理与性能优化技巧,并通过一个学生信息管理系统的实战案例,帮助你快速掌握Java开发技能,适合Java学习与面试准备。
332 2
Java 相关知识点总结含基础语法进阶技巧及面试重点知识
|
6月前
|
算法 Java 测试技术
零基础学 Java: 从语法入门到企业级项目实战的详细学习路线解析
本文为零基础学习者提供完整的Java学习路线,涵盖语法基础、面向对象编程、数据结构与算法、多线程、JVM原理、Spring框架、Spring Boot及项目实战,助你从入门到进阶,系统掌握Java编程技能,提升实战开发能力。
364 0
|
Java Apache Maven
Java百项管理之新闻管理系统 熟悉java语法——大学生作业 有源码!!!可运行!!!
文章提供了使用Apache POI库在Java中创建和读取Excel文件的详细代码示例,包括写入数据到Excel和从Excel读取数据的方法。
183 6
Java百项管理之新闻管理系统 熟悉java语法——大学生作业 有源码!!!可运行!!!
|
7月前
|
存储 安全 Java
从基础语法到实战应用的 Java 入门必备知识全解析
本文介绍了Java入门必备知识,涵盖开发环境搭建、基础语法、面向对象编程、集合框架、异常处理、多线程和IO流等内容,结合实例帮助新手快速掌握Java核心概念与应用技巧。
157 0
|
Java 开发工具 Android开发
Kotlin语法笔记(26) -Kotlin 与 Java 共存(1)
Kotlin语法笔记(26) -Kotlin 与 Java 共存(1)
157 2
|
Java 开发工具 Android开发
Kotlin语法笔记(26) -Kotlin 与 Java 共存(1)
本系列教程笔记详细讲解了Kotlin语法,适合需要深入了解Kotlin的开发者。若需快速学习Kotlin,建议查看“简洁”系列教程。本期重点介绍了Kotlin与Java的共存方式,包括属性、单例对象、默认参数方法、包方法、扩展方法以及内部类和成员的互操作性。通过这些内容,帮助你在项目中更好地结合使用这两种语言。
183 1
|
11月前
|
缓存 安全 Java
java面试-基础语法与面向对象
本文介绍了 Java 编程中的几个核心概念。首先,详细区分了方法重载与重写的定义、发生阶段及规则;其次,分析了 `==` 与 `equals` 的区别,强调了基本类型和引用类型的比较方式;接着,对比了 `String`、`StringBuilder` 和 `StringBuffer` 的特性,包括线程安全性和性能差异;最后,讲解了 Java 异常机制,包括自定义异常的实现以及常见非检查异常的类型。这些内容对理解 Java 面向对象编程和实际开发问题解决具有重要意义。