關於流的關閉:IOUtils.closeQuietly

在我們關閉流時,通常是close放到 finally 中,並在 close 前判斷是否爲 null。但close也會 throw IOException,所以在在 finally 中 也需要 try catch 一下,於是代碼就很長。如下:

 try {
 
 } catch (IOException e) { 

 } finally {
       if (in != null) {
          try {
              in.close();
          } catch (IOException e) {
             
          }
       }
       if (out != null) {
          try {
              out.close();
          } catch (IOException e) {
             
          }
       }
 }       

而如果使用IOUtils.closeQuietly,就方便多了,如下:

 try {
 
 } catch (IOException e) { 

 } finally {
       IOUtils.closeQuietly(in);
       IOUtils.closeQuietly(out);
 }       
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章