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 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 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.
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 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 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----
http://blog.csdn.net/fw0124/article/details/49946975
Java7新语法 -try-with-resources的更多相关文章
- Java之JDK7的新语法探索
Java之JDK7的新语法探索 前言 感谢! 承蒙关照~ 字面量: 各种精致的表达方式: 八进制以0开头,十六进制0X开头,二进制以0B开头. 二进制运算时,应该写成这样才直观: &15 -& ...
- java7新特性之Try-with-resources (TWR)
java7新特性之Try-with-resources (TWR) This change is easy to explain, but it has proved to have hidden s ...
- [C#] 回眸 C# 的前世今生 - 见证 C# 6.0 的新语法特性
回眸 C# 的前世今生 - 见证 C# 6.0 的新语法特性 序 目前最新的版本是 C# 7.0,VS 的最新版本为 Visual Studio 2017 RC,两者都尚未进入正式阶段.C# 6.0 ...
- qt5中信号和槽的新语法
qt5中的连接 有下列几种方式可以连接到信号上 旧语法 qt5将继续支持旧的语法去连接,在QObject对象上定义信号和槽函数,及任何继承QObjec的对象(包含QWidget). connect(s ...
- Qt 5.0+ 中 connect 新语法与重载函数不兼容问题的解决方法,以及个人看法
Qt 5.0+ 版本提供了 connect 的新语法,相比之前的语法新语法可以提供编译期检查,使用也更方便.可是使用过程中发现一个小问题——当某个 signal 和成员函数是重载关系的时候,qmake ...
- .NET中那些所谓的新语法之一:自动属性、隐式类型、命名参数与自动初始化器
开篇:在日常的.NET开发学习中,我们往往会接触到一些较新的语法,它们相对以前的老语法相比,做了很多的改进,简化了很多繁杂的代码格式,也大大减少了我们这些菜鸟码农的代码量.但是,在开心欢乐之余,我们也 ...
- .NET中那些所谓的新语法之二:匿名类、匿名方法与扩展方法
开篇:在上一篇中,我们了解了自动属性.隐式类型.自动初始化器等所谓的新语法,这一篇我们继续征程,看看匿名类.匿名方法以及常用的扩展方法.虽然,都是很常见的东西,但是未必我们都明白其中蕴含的奥妙.所以, ...
- .NET中那些所谓的新语法之三:系统预定义委托与Lambda表达式
开篇:在上一篇中,我们了解了匿名类.匿名方法与扩展方法等所谓的新语法,这一篇我们继续征程,看看系统预定义委托(Action/Func/Predicate)和超爱的Lambda表达式.为了方便码农们,. ...
- .NET中那些所谓的新语法之四:标准查询运算符与LINQ
开篇:在上一篇中,我们了解了预定义委托与Lambda表达式等所谓的新语法,这一篇我们继续征程,看看标准查询运算符和LINQ.标准查询运算符是定义在System.Linq.Enumerable类中的50 ...
随机推荐
- 二叉树后序遍历的非递归算法(C语言)
首先非常感谢‘hicjiajia’的博文:二叉树后序遍历(非递归) 这篇随笔开启我的博客进程,成为万千程序员中的一员,坚持走到更远! 折磨了我一下午的后序遍历中午得到解决,关键在于标记右子树是否被访问 ...
- HDU-2059龟兔赛跑(基础方程DP-遍历之前的所有状态)
Problem Description 据说在很久很久以前,可怜的兔子经历了人生中最大的打击——赛跑输给乌龟后,心中郁闷,发誓要报仇雪恨,于是躲进了杭州下沙某农业园卧薪尝胆潜心修炼,终于练成了绝技,能 ...
- StoryBoard页面联线跳转已经页面之间传参数
1.选中上图黄色.按住Control 把线拖到要要跳转的页面,寻找show. 2.选中联线.在右边Identifier:随便填入一个标示 3.在按钮点击事件加上如下代码 - (IBAction)but ...
- jqTransform——学习(1)
官网:http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/ 转载:http://www.helloweba.com/view- ...
- mnist数据集转换bmp图片
Mat格式mnist数据集下载地址:http://www.cs.nyu.edu/~roweis/data.html Matlab转换代码: load('mnist_all.mat'); type = ...
- 关于IE7 兼容问题
关于a标签的写法(目前测试只针对IE7,IE8及谷歌浏览器): <a onclick = 方法名(参数);></a> 此写法在 IE8以上及谷歌浏览器使用都没有问题,但在I ...
- BZOJ 3110 ZJOI 2013 K大数查询 树套树(权值线段树套区间线段树)
题目大意:有一些位置.这些位置上能够放若干个数字. 如今有两种操作. 1.在区间l到r上加入一个数字x 2.求出l到r上的第k大的数字是什么 思路:这样的题一看就是树套树,关键是怎么套,怎么写.(话说 ...
- 苹果有益让老iPhone变慢以迫使消费者购买新一代的iPhone?
首先,来一组来自谷歌Trends的图片.(谷歌Trends记录了某段时间内相关关键词搜索的次数.) 假设你做数据,那么你应该会有些感觉. 特别是第一幅图,它规律似乎比第二幅更明显,第二幅图仅仅是一个普 ...
- 一键注册控件的批处理(包含x86 和 x64)
@echo off if "%PROCESSOR_ARCHITECTURE%"=="x86" goto x86 if "%PROCESSOR_ARCH ...
- canvas-画蜗牛
<!doctype html><html lang="en"> <head> <meta charset="UTF-8" ...