IO-文件流-两种正确关闭资源的方法

方法一:传统方法

也是最基本的资源关闭的方法

 void test1() {
        File file = new File("a.txt");
        File file2 = new File("b.txt");
 //在try 代码块外声明流对象,保证在finally块里能用
        InputStream in = null;
        OutputStream out = null;
        try {
            //可能出现异常的代码
            in = new FileInputStream(file);
            out = new FileOutputStream(file2);
            byte[] b = new byte[4];//创建缓存区,存储读取的数据
            int len = -1;//表示已经读取了多少个字节,如果len返回-1,表示已经读到最后

            while ((len = in.read(b)) != -1) {
                //打印出读取的数据
                System.out.println(new String(b, 0, len));
                out.write(b, 0, len);
            }

        } catch (Exception e) {
            //处理异常
            e.printStackTrace();
        } finally {
            //一定会执行的代码
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

方法二:java7开始的自动资源关闭

模式:

try(
//打开资源代码
){
//可能出现异常的代码
}catch(Exception e){
e.printStackTrace();
}

void test2() {
        File file = new File("a.txt");
        File file2 = new File("b.txt");
        try (
                //打开资源代码
                InputStream in = new FileInputStream(file); 
                OutputStream out = new FileOutputStream(file2);

        ) {
            //可能出现异常的代码
            byte[] b = new byte[4];//创建缓存区,存储读取的数据
            int len = -1;//表示已经读取了多少个字节,如果len返回-1,表示已经读到最后
            while ((len = in.read(b)) != -1) {
                //打印出读取的数据
                System.out.println(new String(b, 0, len));
                out.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值