2009-07-02 127 views
1

只是認爲當我打開我的文件,然後當我想寫入一些東西時,會拋出一個異常,並且如果我在try塊中使用file.close(),那麼由於該異常將不起作用, 我應該在哪裏關閉我的文件?如何在特殊情況下關閉文件?

+0

,當我在寫file.close()finally塊,它將顯示創建一個名爲文件中的局部變量的錯誤。:( – Johanna 2009-07-02 06:48:58

回答

5

正確的方法,這樣做是:

FileOutputStream out = null; 
try { 
    out = ... 
    ... 
    out.write(...); 
    ... 
    out.flush(); 
} catch (IOException ioe) { 
    ... 
} finally { 
    if(out!=null) { 
    try { 
     out.close(); 
    } catch (IOException ioe) { 
     ... 
    } 
    } 
} 
1

你應該使用finally塊。但是close方法也會拋出一個IOException異常,所以你應該把它包含在一個try-catch塊中。

This link may be helpful。

+0

有近拋出IOException是一個不好的設計決定我意見 – butterchicken 2009-07-02 06:56:45

0

使用finally塊:

File f; 
try { 
f = .... 
.. use f ... 
} /* optional catches */ 
finally { 
if (f != null) f.close(); 
} 
0

我用兩個嘗試catch塊。

一個我打開文件+一個布爾讓我知道該文件已成功打開。 第二個我寫東西的地方(檢查布爾如果打開是成功的)。

Try 
    { 
     //Open file. If success. 
     bSuccess = true. 
    } 
    catch 
    { 

    } 

    try 
    { 
    //check bool 
    If(bSuccess) 
    { 
    //Do write operation 
    } 
    } 
    catch 
    { 
    } 
    finally 
    { 
     if(bSuccess) 
    { 
     File.close(); 
    } 
    } 
+0

我喜歡mfx的建議 – 2009-07-02 06:58:22

0

大衛拉比諾維茨的答案是正確的,但它可以得到與使用Apache Commons IO簡單。對於finally子句中複雜的try-block,它有一個方法,用於在沒有異常的情況下關閉任何Stream。有了這個,你可以這樣寫:

FileOutputStream out = null; 
try { 
    out = ... 
    ... 
    out.write(...); 
    ... 
    out.flush(); 
} catch (IOException ioe) { 
    ... 
} finally { 
    if(out!=null) { 
    org.apache.commons.io.IOUtils.closeQuietly(out); 
    } 
} 
+0

爲什麼downvote? – Mnementh 2009-07-02 10:15:35

2

資源的一般模式是acquire; try { use; } finally { release; }。如果您嘗試重新排列,那麼您通常會在您未釋放鎖的情況下結束鎖定。請注意,通常不需要使用空檢查混亂。如果您需要從中獲得例外,請使用try-catch環繞所有代碼。所以

try { 
    final InputStream in = new FileInputStream(file); 
    try { 
     ... 
    } finally { 
     in.close(); 
    } 
} catch (IOException exc) { 
    throw new SomeException(exc); 
} 
相關問題