字节流的操作后续

续上篇,完成了复制一jpg文件的时候还有一处问题,就是代码运行过程中,可能会抛出异常,程序可能会终止,这样close操作就会运行不到
从而可能导致文件资源泄露.那么我们应该使用try{}catch{}语句块来包裹之前的语句.
所以对上篇结尾的代码就需要改进
得到:


    private static void copyFile(String srcPath, String destPath) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try{
            fileInputStream = new FileInputStream(srcPath);
            fileOutputStream = new FileOutputStream(destPath);
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer,0, len);
            }
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 

但是改进后的代码也有问题,如果输入流对象和输出流对象在初始化时就抛出了异常,那么两个变量就指向空,直接执行finally中代码就会发生空指针异常
所以仍需改进为:


    private static void copyFile(String srcPath, String destPath) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try{
            fileInputStream = new FileInputStream(srcPath);
            fileOutputStream = new FileOutputStream(destPath);
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer,0, len);
            }
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileInputStream != null) {
                    fileInputStream.close();
                }
                if(fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

改进之后代码没有太大问题了,但是非常不美观,嵌套语句太多,看起来复杂,所以还有最后这种写法

private static void copyFile2(String srcPath, String destPath) {
        try(FileInputStream fileInputStream = new FileInputStream(srcPath);
            FileOutputStream fileOutputStream = new FileOutputStream(destPath)
        ){
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer,0, len);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

改写后的copyFile方法就更加美观了
写成这样就不需要再显示调用close方法,自动调用并处理,但是前提是这个类必须要实现Closable接口.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值