天天看點

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, , 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

Java中為IO流寫一個快速關閉流的小工具

可以看到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, , fileOutputStream);
        } catch (Exception e) {          
            e.printStackTrace();
        } finally {

            ColseUtil.closeIt(fileOutputStream );
        }
    }
           

比起原來的那個代碼是不是看上去會順眼得多,哈哈。當然,我們在友善的同時産生了新的類,不過這點消耗能換來更好的閱讀性,何樂而不為呢?