资源自动关闭接口Closeable解析
定义
Closeable
:是可以关闭的数据源或目标。调用 close 方法可释放对象保存的资源(如打开文件)。
Closeable
的UML图
AutoCloseable
:JDK提供的自动关闭接口
Closeable
:JDK提供的关闭接口,继承AutoCloseable
MyInputStream
:自定义的接口,模拟JDK的InputStream
MyInputStreamImpl
:MyInputStream
的实现类
实例代码如下,演示一下自动关闭的功能:
public interface MyInputStream extends Closeable {
}
/**
* @Description TODO
* @Author zhangwy
* @Date 2021/6/1113:30
* @Version 1.0
*/
public class MyInputStreamImpl implements MyInputStream{
@Override
public void close() throws IOException {
System.out.println("关闭资源");
}
}
/**
* @Description TODO
* @Author zhangwy
* @Date 2021/6/1113:31
* @Version 1.0
*/
public class Client {
public static void main(String[] args) throws UnsupportedEncodingException {
try (MyInputStream myInputStream = new MyInputStreamImpl()){
System.out.println("todo business");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("---------------------------------------");
try{
MyInputStream myInputStream2 = new MyInputStreamImpl();
}catch (Exception e){
e.printStackTrace();
}
}
}
运行Client
结果如下:
todo business
关闭资源
todo business
从运行结果可以看出,只要把需要关闭的资源放在try()里面,代码会自动调用close()方法将资源关闭掉。