Try-with-resource在进行资源关闭时候替换try-catch-finally

try-with-resource是Java1.7引入的特性,用于更优雅地管理需要关闭的资源,如文件流或数据库连接。它要求资源实现AutoCloseable接口,然后在try语句中声明,编译器会在适当的时候自动调用close方法,避免了手动在finally块中关闭资源的需要,从而减少了资源泄漏的风险。
摘要由CSDN通过智能技术生成

Try-with-resource在进行资源关闭时候替换try-catch-finally

参考:https://zhangshuai.blog.csdn.net/article/details/88542224

概述

网络连接或者文件资源都需要自己去手动释放关闭,如InputStream,OutStream,SqlConnection等

JDK1.7开始,java引入了 try-with-resources 声明,将 try-catch-finally 简化为 try-catch,这其实是一种语法糖,在编译时会进行转化为 try-catch-finally 语句。新的声明包含三部分:try-with-resources 声明、try 块、catch 块。它要求在 try-with-resources 声明中定义的变量实现了 AutoCloseable 接口,这样在系统可以自动调用它们的close方法,从而替代了finally中关闭资源的功能。

//常见Java文件资源关闭
BufferedWriter writer = null;
try {
    writer = Files.newBufferedWriter(file, charset);
    writer.write(s, 0, s.length());
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
} finally {
    if (writer != null) writer.close();
}

  • 上面的代码必须在finally代码块里面进行资源的关闭,否则随着程序不断运行,资源泄露会累计成重大生产事故。
try-with-resource
  • 这里我们可以使用Java1.7新增的try-with-resource语法糖来打开资源,无需自己手动进行关闭资源

  • public class TryWithResource {
    
        public static void main(String[] args) {
            try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
                 BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
                int b;
                while ((b = bin.read()) != -1) {
                    bout.write(b);
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
  • 所谓的try-with-resource我理解的就是在原来的try-catch-finaly上面减少了finally代码块,让程序自动执行close方法

  • 这里要记住一点,这些资源必须要实现AutoCloseAble接口

  • 
    //关闭单一资源
    public class Demo {    
        public static void main(String[] args) {
            try(Resource res = new Resource()) {
                res.doSome();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    class Resource implements AutoCloseable {
        void doSome() {
            System.out.println("do something");
        }
        @Override
        public void close() throws Exception {
            System.out.println("resource is closed");
        }
    }
    
    //结果
    do something
    resource is closed
    
  • 
    //关闭多个资源
    public class Main2 {    
        public static void main(String[] args) {
            try(ResourceSome some = new ResourceSome();
                 ResourceOther other = new ResourceOther()) {
                some.doSome();
                other.doOther();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    class ResourceSome implements AutoCloseable {
        void doSome() {
            System.out.println("do something");
        }
        @Override
        public void close() throws Exception {
            System.out.println("some resource is closed");
        }
    }
    
    class ResourceOther implements AutoCloseable {
        void doOther() {
            System.out.println("do other things");
        }
        @Override
        public void close() throws Exception {
            System.out.println("other resource is closed");
        }
    }
    
    //结果
    do something
    do other things
    other resource is closed
    some resource is closed
    
    
    
    
    
    
更简便理解-下面两部分代码相同

区别就是:try-with-resource部分

  1. 继承了AutoCloseAble接口
  2. 少了finally代码块
  3. 其他都是一摸一样的
public class TryWithResource implements AutoCloseable {

    private int age = 18;

    @Override
    public void close() throws Exception {
        System.out.println("this is close 方法");
    }

    public static void main(String[] args) {
        try (TryWithResource tryWithResource = new TryWithResource()) {
            System.out.println(tryWithResource.age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class TryWithResource{

    private int age = 18;

    public void close() throws Exception {
        System.out.println("this is close 方法");
    }

    public static void main(String[] args) {
        TryWithResource tryWithResource = new TryWithResource();
        try {
            System.out.println(tryWithResource.age);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                tryWithResource.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值