每次在我们调用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 ); } }比起原来的那个代码是不是看上去会顺眼得多,哈哈。当然,我们在方便的同时产生了新的类,不过这点消耗能换来更好的阅读性,何乐而不为呢?
新闻热点
疑难解答