try-with-resources语法块说起

我们知道java7中引入了新的语法块try-with-resources:实现了java.lang.AutoCloseable的对象都可以作为资源,在try后面的括号类声明实例化,在后面的{...}语句块执行完后被自动关闭(close()方法被自动调用)。例如:在java7前,我们需要这样定义语句:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void writeFile(String path,byte[] data){
OutputStream os = null;
try {
os = new FileOutputStream(path);
os.write(data);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os!=null){
os.close();
}
}
}

而在java7后,可以变成这样:

1
2
3
4
5
6
7
8
public void writeFile(String path,byte[] data){
try ( OutputStream os = new FileOutputStream(path)){
os.write(data);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}

CloseableAutoCloseable的关系与区别

AutoCloseable的源码如下:

1
2
3
4
5
6
/**
* @since 1.7
*/
public interface AutoCloseable {
void close() throws Exception;
}

Closeable的源码如下:

1
2
3
4
5
6
/**
* @since 1.5
*/
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}

由上可知Closeable在jdk1.5中就定义了,而AutoCloseable在jdk1.7才被引入,并且Closeable继承了AutoCloseable。为什么要这样设计呢?答案很简单,仔细查看源码就可以知道原因:
因为Closeableclose()方法只会抛出IOException异常,而AutoCloseableclose()方法抛出的是Exception异常。如此一来try-with-resources的适用性就更大了。

参考

  1. https://stackoverflow.com/questions/19572537/why-is-autocloseable-the-base-interface-for-closeable-and-not-vice-versa