Java中为IO流写一个快速关闭流的小工具

每次在我们调用Java中流操作的时候,在结束的时候都要调用它的close()方法将其关闭,产生一大堆try…catch…finally,不仅让人看着心烦还容易让人产生错误,今天我们就来解决一下这头痛的问题。

情景再现
假设在ImageLoder类中假设有这样一段代码:

  public void put(String url, Bitmap bitmap) {

        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(cacheDir + "/pic/");
            fileOutputStream = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {          
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

在上述代码中,try…catch…finally使得其可读性下降,而且容易让人出错,比如将代码写到错误的括号级层中去。

有没有办法解决这种因为需要close而产生的让人烦的问题呢?

我们通过查看FileOutputStream 的API文档 查看官方API
这里写图片描述

可以看到FileOutputStream 实现了Closeable接口,通过API可以得知Closeable一个close方法。(读者可以自行查看,上面给出了API查看地址)于是,我们可以写一个这样的ColseUtil类

public class ColseUtil{

    public static void closeIt(Closeable closeable){

         if (closeable!= null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }

}

这样原来的代码就可以这样写

public void put(String url, Bitmap bitmap) {

        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(cacheDir + "/pic/");
            fileOutputStream = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {          
            e.printStackTrace();
        } finally {

            ColseUtil.closeIt(fileOutputStream );
        }
    }

比起原来的那个代码是不是看上去会顺眼得多,哈哈。当然,我们在方便的同时产生了新的类,不过这点消耗能换来更好的阅读性,何乐而不为呢?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值