JDK7资源释放:try-with-resource

本文介绍了Java7引入的try-with-resources特性,它提供了一种更优雅的方式来处理程序中需要手动关闭的资源,如文件流。通过在try语句中声明资源,资源会在finally块执行之前自动关闭,避免了try-finally的复杂性。
摘要由CSDN通过智能技术生成

一、介绍

jdk7开始比try-fianlly更简单的资源释放方案,try-finally代码臃肿,不太优雅。于是有了更加优雅的try-with

-resource。

二、使用样式

在try后面写一对小括号,将你要用到的资源比如流对象写进里面,当你使用完流对象的时候,它会自动帮你释放资源(该资源使用完毕后,会自动调用其close()方法,完成对资源的释放!)

三、代码演示

package com.yucako.d4_tryFinally;

import java.io.FileInputStream;
import java.io.FileOutputStream;


public class tryRe3 {
    public static void main(String[] args) {
        try (
                FileInputStream is = new FileInputStream("D:jj/kk");
                FileOutputStream os = new FileOutputStream("D:dd/kk");
                //注意事项:只能写资源对象(流对象)
                //什么时流对象:实现了AutoCloseable接口;资源对象里面都有close方法
                
                ){
                byte [] bytes = new byte[1024];
                int len ;
                while ((len=is.read())!=-1){
                    os.write(bytes,0,len);
                }
          
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
测试:是否会自动运行close
package com.yucako.d4_tryFinally;

import java.io.FileInputStream;
import java.io.FileOutputStream;


public class tryRe3 {
    public static void main(String[] args) {
        try (
//                FileInputStream is = new FileInputStream("D:jj/kk");
//                FileOutputStream os = new FileOutputStream("D:dd/kk");
                //注意事项:只能写资源对象(流对象)
                //什么时流对象:实现了AutoCloseable接口;资源对象里面都有close方法
                MyClose mm = new MyClose();//测试流对象是否自动运行 close
                ){
//                byte [] bytes = new byte[1024];
//                int len ;
//                while ((len=is.read())!=-1){
//                    os.write(bytes,0,len);
//                }
            System.out.println(mm);//测试流对象是否自动运行 close
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
package com.yucako.d4_tryFinally;

public class MyClose implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("关闭了与某个硬盘的连接");
    }
}

结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值