Closeable

JDK7之前
JDK7之前的版本在释放资源的时候,使用的try-catch-finally来操作资源。

其中,try代码块中使用获取、修改资源,catch捕捉资源操作异常,finally代码块来释放资源。

try {

fos = new FileOutputStream("test.txt");
dos = new DataOutputStream(fos);
dos.writeUTF("JDK7");

} catch (IOException e) {

// error处理

} finally {

fos.close();
dos.close();

}
问题来了,finally代码块中的fos.close()出现了异常,将会阻止dos.close()的调用,从而导致dos没有正确关闭而保持开放状态。

解决方法是把finally代码块中的两个fos和dos的关闭继续套在一个try-catch-finally代码块中。

FileOutputStream fos = null;
DataOutputStream dos = null;
try {

fos = new FileOutputStream("test.txt")
dos = new DataOutputStream(fos);
// 写一些功能

} catch (IOException e) {

// error处理

} finally {

try {
    fos.close();
    dos.close();
} catch (IOException e) {
    // log the exception
}

}

JDK7及之后
JDK7之后有了带资源的try-with-resource代码块,只要实现了AutoCloseable或Closeable接口的类或接口,都可以使用该代码块来实现异常处理和资源关闭异常抛出顺序。

try(FileOutputStream fos = new FileOutputStream("test.txt")){

// 写一些功能

} catch(Exception e) {

// error处理

}
我们可以发现,在新版本的资源try-catch中,我们已经不需要对资源进行显示的释放,而且所有需要被关闭的资源都能被关闭。
需要注意的是,资源的close方法的调用顺序与它们的创建顺序是相反的。

猜你喜欢

转载自yq.aliyun.com/articles/696489