在下面的代碼:Java輸入流如何關閉?
DataInputStream in = new DataInputStream(
new BufferedInputStream(new FileInputStream(file)));
in.close();
我是否需要除關閉「頂級」流關閉2其他流?
在下面的代碼:Java輸入流如何關閉?
DataInputStream in = new DataInputStream(
new BufferedInputStream(new FileInputStream(file)));
in.close();
我是否需要除關閉「頂級」流關閉2其他流?
如果你看DataInputStream
的來源,你可以看到它也關閉了底層流。所以你不需要。這對所有類型的流都是(或應該)是真的。
Karazi,是正確的暗示。此外,爲了獲得一個想法和更多的見解,Java IO API實際上是使用裝飾器模式實現的。您可以在維基上查看decorator pattern。
我會堅持封閉在一個finally塊,以確保它在正常情況下被刷新以防異常。
public void tryToDoWhatever() throws Exception
{
DataInputStream in = null;
try
{
in = new DataInputStream(
new BufferedInputStream(new FileInputStream(file)));
}
finally
{
if (in != null)
in.close();
}
}
是的你是對的,但是這引發了一個新的問題:如何處理IOException可以拋出in.close ??在try塊中加入try catch或者在上層轉發它? – 2010-10-20 08:59:59
是的,這是不是很普遍我通常這樣做 – willcodejavaforfood 2010-10-20 09:00:48
@Manuel Selva-我總是將異常處理與業務邏輯分開。我會有一個名爲'doWhatever()'的方法,它在try/catch塊中調用tryToDoWhat來處理那裏的異常。 – willcodejavaforfood 2010-10-20 09:04:04
我會利用這個機會回答我之前已經提出的答案。
通過使用Project Lombok您可以讓Lombok正確關閉您的流。 詳情可以發現here。
更重要的是,它被記錄在案。它有點碎片化,但是'DataInputStream'繼承'FilterInputStream'的'close',它記錄了它在底層的'InputStream'上的'close':http://download.oracle.com/javase/6/docs/api /java/io/FilterInputStream.html所以你知道這個行爲不僅僅是特定實現的副作用。 – 2010-10-20 08:34:53
其實它適用於所有類型的'Closeable'# – 2010-10-20 08:59:55
@Sherwin ...只要他們正確地實施「合同」:-) – 2010-10-20 10:12:31