JAVA IO流中1.7之后关闭流的处理

文章介绍了两种关闭JavaIO流的方法:一是手动关闭,例如在示例代码中,流在使用后调用close()方法进行关闭;二是Java7及以后版本引入的try-with-resources语句,它能自动关闭资源,简化了异常处理并确保流在操作完成后被正确关闭。
摘要由CSDN通过智能技术生成

1.io流手动关闭

每个io流执行完毕以后,都会从下到上,依次调用close();方法。

public class Demo3 {
    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:/aaa/22.png"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:/bbb/xixi.png"));
        byte[] buf = new byte[4 * 1024];
        int length;
        while ((length = bis.read(buf)) != -1) {
            bos.write(buf, 0, length);
        }
        bos.close();
        bis.close();
    }
}

2.用异常处理

jdk1.7以后,try--catch自动关闭流,不需要手动关闭。主要因为,try--catch自动把流的异常给关闭。

public class Demo1 {
    public static void main(String[] args)  {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("E:\\11.jpg");
            fos = new FileOutputStream("D:\\encohe.jpg");
            BufferedInputStream bis = new BufferedInputStream(fis);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            byte[] bytes1 = new byte[4 * 1024];
            int temp;
            while ((temp = bis.read(bytes1)) != -1) {
                bos.write(bytes1,0, temp);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值