Java专题 文件IO流 try-with-resources写法

本文介绍Java 7及更高版本中自动资源管理功能,展示如何使用try-with-resources语句简化文件复制过程,提高代码可读性和维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

支持版本

JDK1.7及以上

好处

可以自己帮你关闭IO流,不用手动写,不用try catch 套try catch的写,搞得很难看;

代码如下

这里做演示和记录,printStackTrace就不做处理了

 try (
     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\YvYv\\Desktop\\13.png")));
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\YvYv\\Desktop\\66.png")));
      ) {
            byte[] bytes = new byte[bis.available()];
            int len;

            while ((len = bis.read(bytes))!=-1) {
                bos.write(bytes,0,len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值