如何使用 try-with-resources 优雅地关闭资源

今天学习下Java 7中引入的try-with-resources语法糖,一个非常有用的特性,它使得在代码中使用资源(例如文件或数据库连接)变得更加简单、方便和安全。所有被打开的系统资源,比如流、文件或者Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。

try(资源变量=创建资源对象){
    
}catch(){
    
}

例如 InputStream, OutputStream ,Connection, Statement, ResultSet等接口都实现了资源对象关闭接口AutoCloseable,使用 try-with-resource可以不用写finally块,编译器会帮助生成关闭资源的代码,例如:

public class TryWithResourceNewTest {
    public static void main(String[] args) {
        try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("sanFengIn.txt")));
             BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("sanFengOut.txt")))) {
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果不用这个语法糖,手动在finally块中关闭,则代码显得非常臃肿。

public class TryWithResourceOldTest {
    public static void main(String[] args) {
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        try {
            bin = new BufferedInputStream(new FileInputStream(new File("sanFengIn.txt")));
            bout = new BufferedOutputStream(new FileOutputStream(new File("sanFengOut.txt")));
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (bin != null) {
                try {
                    bin.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                finally {
                    if (bout != null) {
                        try {
                            bout.close();
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

但是 try-with-resources 这几个关键点要记住:

 1. try() 里面的类,必须实现了 AutoCloseable 接口 
 2.try() 代码中声明的资源被隐式声明为 final
 3  使用分号分隔,可以声明多个资源

try-with-resources 从反编译后的代码来看,编译器自动帮我们生成了 finally 块,并且在里面调用了资源的 close() 方法,所以例子TryWithResourceOldTest 中的close() 方法会在运行的时候被执行。

参考资料
try-with-resources语法详解
如何使用 try-with-resources 优雅地关闭资源
Java的try-with-resources
try-with-resource

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值