try-with -resource学习

try-with-resource 自动关闭Closeable接口的资源

Java中,JVM的垃圾回收机制可以对内部资源实现自动回收,给开发者带来极大的遍历,但是JVM对外部资源(调用了底层操作系统的资源)的引用却无法自动回收,例如数据库连接,网络连接以及输入输出IO流等。这些连接就需要我们手动去关闭,不然会导致外部资源泄露,连接池溢出以及文件被异常占用等。

JDK7之后,新增了“try-with--resource”。它可以自动关闭实现了AutoCloseable接口的类,实现类需要实现close()方法。“try-with-resources”声明,将try-catch-finally简化为try-catch,这其实是一种语法糖,字编译时仍然会转化为try-catch-finally语句;

如下FileReader:

以下两种都是关闭了流资源reader:

public class CloseTest {
    public static void main(String[] args) {
        FileReader reader =null;
        try {
             reader = new FileReader("D:\\huangzheng\\a.txt");
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

package com.to.filter;

import java.io.FileReader;
import java.io.IOException;

public class CloseTest {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("D:\\huangzheng\\1.txt");)
        {
            char[] a = new char[1024];
            int read = reader.read(a);
            String s = new String(a, 0, read);
            System.out.println(s);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

try{}中写流关闭,如果发生异常不会关闭流,所以要么使用finally或者try()中实现流的关闭

 

对比:try-with-finally:是手动关流
try-with-resource:自动关流,就是写在try()中,语法糖看起来很别扭 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值