使用AutoCloseable 实现自动关闭资源

一、认识AutoCloseable

AutoCloseable接口位于java.lang包下,从JDK1.7开始引入。

 

1.在1.7之前,我们通过try{} finally{} 在finally中释放资源。

 

在finally中关闭资源存在以下问题:

1、自己要手动写代码做关闭的逻辑;

2、有时候还会忘记关闭一些资源;

3、关闭代码的逻辑比较冗长,不应该是正常的业务逻辑需要关注的;

 

2.对于实现AutoCloseable接口的类的实例,将其放到try后面(我们称之为:带资源的try语句),在try结束的时候,会自动将这些资源关闭(调用close方法)。

 

带资源的try语句的3个关键点:

1、由带资源的try语句管理的资源必须是实现了AutoCloseable接口的类的对象。

2、在try代码中声明的资源被隐式声明为fianl。

3、通过使用分号分隔每个声明可以管理多个资源。

二、代码演示

复制代码

public class AutoCloseableDemo {
    public static void main(String[] args) {
        try (AutoCloseableObjecct app = new AutoCloseableObjecct()) {
            System.out.println("--执行main方法--");
        } catch (Exception e) {
            System.out.println("--exception--");
        } finally {
            System.out.println("--finally--");
        }
    }

    //自己定义类 并实现AutoCloseable
    public static class AutoCloseableObjecct implements AutoCloseable {
        @Override
        public void close() throws Exception {
            System.out.println("--close--");
        }

    }


    @Test
    public void demo2() {

        //JDK1.7之前,释放资源方式
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //1.7之后,只要实现了AutoCloseable接口
        try (FileInputStream fileInputStream2 = new FileInputStream("")) {

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

复制代码

 

  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值