JAVA 资源自动释放try(){}catch{}

从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

带资源的try catch  

 

1.自动释放资源格式:

try(
    资源
     ){

    }catch{

    }

2.最初关闭资源方式

private static void customBufferStreamCopy(File source, File tar) {
    InputStream fis = null;
    OutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(tar);
 
        byte[] buf = new byte[8192];
 
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
    }
}

3.现在使用关闭方式.,则不需要在finally中进行数据关闭。将资源关闭不需要写代码操作

private static void customBufferStreamCopy(File source, File tar) {
    InputStream fis = null;
    OutputStream fos = null;
    try (
         fis = new FileInputStream(source),
        fos = new FileOutputStream(tar)
        ){
       
        byte[] buf = new byte[8192];
 
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    } 
}

 

4.前提是资源必须:这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。

例如:以下这些类或者子接口都支持此方法,因为他们都实现了  java.lang.AutoCloseable

5.例如我们可查看:

 我们将FIleInputStream 放置try()中

点进去看FIleInputStream.发现继承至InputStream

点进去看InputStream.发现实现了Closeable

点进去看Closeable.发现实现了AutoCloseable

发现Closeable 继承至AutoCloseable .那么即满足了带资源关闭的基本要求。当try 中的{ } 执行完后,将会自动关闭资源

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值