资源自动关闭接口Closeable解析

资源自动关闭接口Closeable解析

定义

Closeable:是可以关闭的数据源或目标。调用 close 方法可释放对象保存的资源(如打开文件)。

Closeable的UML图

在这里插入图片描述

AutoCloseable:JDK提供的自动关闭接口

Closeable:JDK提供的关闭接口,继承AutoCloseable

MyInputStream:自定义的接口,模拟JDK的InputStream

MyInputStreamImplMyInputStream的实现类

实例代码如下,演示一下自动关闭的功能

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()方法将资源关闭掉。

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值