1 Autocloseable接口简介
出现自jdk 1.7
- 一个可以一直保存资源(如文件或socket句柄)的直到关闭的对象。当退出try-with-resources块时,自动调用AutoCloseable对象的close()方法。这种构造确保了资源可以及时释放,避免了可能发生的资源耗尽异常和错误。
- 注意
对于必须完全通用地运行的代码,或当知道AutoCloseable实例需要释放资源时,建议使用try-with-resources结构。然而当使用支持基于I/O和非I/O的Stream时,对非I/O使用try-with-resources块一般是不必要的。
2 代码演示
2.1 自定义类
class Main {
public static void main(String[] args) {
try(AutoCloseable autoCloseable = new AutoCloseableDemo()) {
System.out.println("this is main method");
} catch (Exception e) {
e.printStackTrace();
System.out.println("this is Exception");
}finally {
System.out.println("this is finally");
}
}
}
class AutoCloseableDemo implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("Now, It's closed!");
}
}
2.2 用例
以FileInputStream为例
- jdk 1.7之前
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class Main {
public void test() {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
- jdk 1.7之后
由于FileInputStream实现了AutoCloseable接口,故可以写:
class Main {
public void test() {
FileInputStream fileInputStream = null;
try(FileInputStream fileInputStream1 = new FileInputStream("")) {
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}