2012-11-05 67 views
3

當我管理IO時,發現問題。我曾經這樣關閉它:如何關閉IO?

try { 
     // my code 
    } catch (Exception e) { 
     // my code 
    } finally{ 
     if (is != null) { 
      is.close(); 
     } 
    } 

但是close方法也會拋出異常。如果我有一個以上的IO,我必須關閉所有的IO。所以代碼可能是這樣的:

try { 
    // my code 
} catch (Exception e) { 
    // my code 
} finally{ 
    if (is1 != null) { 
     is1.close(); 
    } 
    if(is2 != null{ 
     is2.close(); 
    } 
    // many IOs 
} 

如果is1.close()拋出異常,is2,is3不會自行關閉。所以我必須輸入許多try-catch-finally來控制它們。有沒有其他解決問題的方法?

+0

拋出的異常是什麼? –

+0

可能重複的[在finally塊中拋出異常](http://stackoverflow.com/questions/481446/throws-exception-in-finally-blocks) – dmeister

回答

3

您可以使用Apache IOUtils的​​方法,而不是重新發明方向盤。這些方法壓縮了close()發出的任何IOException,並且還處理參數爲null的情況。

您應該注意的唯一事情就是您不要在具有未刷新數據的輸出流上調用它。如果你這樣做,並沖洗失敗,你不會聽到它。如果你寫的數據很重要,不知道刷新失敗會是一件壞事。

1

我使用這個小靜態工具類,原則是如果你真的必須做一些事情(任何事情),錯誤的處理或最終阻止,然後至少撕毀和執行該死的事情一次,而不是亂拋垃圾從任務分心的應用程序代碼在眼前:

package krc.utilz.io; 

import java.io.Closeable; 
import krc.utilz.reflectionz.Invoker; 

public abstract class Clozer 
{ 
    /** 
    * close these "streams" 
    * @param Closeable... "streams" to close. 
    */ 
    public static void close(Closeable... streams) { 
    Exception x = null; 
    for(Closeable stream : streams) { 
     if(stream==null) continue; 
     try { 
     stream.close(); 
     } catch (Exception e) { 
     if(x!=null)x.printStackTrace(); 
     x = e; 
     } 
    } 
    if(x!=null) throw new RuntimeIOException(x.getMessage(), x); 
    } 

    /** 
    * Close all the given objects, regardless of any errors. 
    * <ul> 
    * <li>If a given object exposes a close method then it will be called. 
    * <li>If a given object does NOT expose a close method then a warning is 
    * printed to stderr, and that object is otherwise ignored. 
    * <li>If any invocation of object.close() throws an IOException then 
    *  <ul> 
    *  <li>we immediately printStackTrace 
    *  <li>we continue to close all given objects 
    *  <li>then at the end we throw an unchecked RuntimeIOException 
    *  </ul> 
    * </ul> 
    * @param Object... objects to close. 
    */ 
    public static void close(Object... objects) { 
    Exception x = null; 
    for(Object object : objects) { 
     if(object==null) continue; 
     try { 
     Invoker.invoke(object, "close", new Object[]{}); 
     } catch (NoSuchMethodException eaten) { 
     // do nothing 
     } catch (Exception e) { 
     e.printStackTrace(); 
     x = e; 
     } 
    } 
    if(x!=null) throw new RuntimeIOException(x.getMessage(), x); 
    } 

} 

注意最後一個特寫例外,如果有的話,還是拋出,不像普通try{stream1.close();}catch{} try{stream2.close();}catch{}虎頭蛇尾。

乾杯。基思。

+0

'for(Closeable stream:streams)'---- Streams is一個IO數組?如是!如何聲明一個IO數組? – Bernard