2011-12-28 92 views
19

是否有無論如何檢查OutputStream是否已關閉而未嘗試寫入並捕獲IOException如何檢查OutputStream是否關閉

例如,請考慮以下做作方法:

public boolean isStreamClosed(OutputStream out){ 
    if(/* stream isn't closed */){ 
     return true; 
    }else{ 
     return false; 
    } 
} 

您能夠利用替代/* stream isn't closed */

+1

什麼是你需要解決的根本問題? – 2011-12-28 12:28:50

+1

我懷疑OP想避免處理異常。 ;) – 2011-12-28 12:35:27

+0

從我的思維防禦性角度思考我可能會收到什麼樣的錯誤輸入,但它更像是一個假設性問題,再加上「java檢查outputstream是否關閉」的頂級google結果指向http:// stackoverflow。com/questions/2607515/how-do-i-check-if-output-stream-of-a-socket-is-closed這似乎並沒有真正回答這個問題 – chrisbunney 2011-12-28 12:36:37

回答

19

基礎流可能不知道它的關閉,直到你試圖寫它(例如,如果一個插座的另一端關閉它)

最簡單的方法就是使用它,處理它是否關閉,會發生什麼然後,而不是先測試它。

不管你測試什麼,總是有機會得到一個IOException,所以你不能避免異常處理代碼。添加此測試可能會使代碼複雜化。

+0

這個答案與其他人分開的是什麼沒有'isClosed()',_「這樣的方法的理由:」在你嘗試寫入它之前,底層的流可能不知道它關閉「_,因此被接受,謝謝:) – chrisbunney 2012-01-02 12:57:01

+0

isClosed()關閉()在你的結尾。這不是大多數人希望它做的事情。 ;) – 2012-01-02 14:39:32

2

OutputStream本身不支持這種方法。 Closable接口的定義方式是,一旦調用close(),您將要處置該OutputStream。

也許你應該重新審視一下應用程序的設計,並檢查你爲什麼沒有這樣做,結果你的應用程序中仍然會運行一個封閉的OutputStream實例。

1

不。如果你實現自己的,你可以寫一個isClosed方法,但如果你不知道具體的類,那麼不會。 OutputStream只是一個抽象類。這是它的實現:

/** 
* Closes this output stream and releases any system resources 
* associated with this stream. The general contract of <code>close</code> 
* is that it closes the output stream. A closed stream cannot perform 
* output operations and cannot be reopened. 
* <p> 
* The <code>close</code> method of <code>OutputStream</code> does nothing. 
* 
* @exception IOException if an I/O error occurs. 
*/ 
public void close() throws IOException { 
} 
+0

是不是'OutputStream'抽象類,因此它可以提供一些實現? – chrisbunney 2011-12-28 12:38:09

+0

是的,對不起,我的壞。它並沒有。 – Kylar 2011-12-28 12:42:52

+1

是的,它不會像@亞歷克斯建議在他的答案(http://stackoverflow.com/a/8655939/110255) – chrisbunney 2011-12-28 12:44:46

8

不幸的是,OutputStream API沒有像isClosed()這樣的方法。

所以,我只知道一個明確的辦法:創建StatusKnowingOutputStream類包裝任何其他輸出流,並實現其close()方法如下:

public void close() { 
    out.close(); 
    closed = true; 
} 

現在添加方法isClosed()

public boolean isClosed() { 
    return closed; 
} 
+0

然而,這應該永遠不會在任何應用程序中要求。如果你自己的代碼關閉了流 - 那麼它也應該處理它的狀態(關閉/打開)。如果你從一些第三方庫中獲取流 - 它應該提供一些'boolean canIUseTheStream()'方法。 – bezmax 2011-12-28 13:02:59

+0

@bezmax,處理它的狀態可能會有點困難,比方說,如果你期望在你的業務方法中關閉它(你需要把它關閉發送到別的地方),但是你需要在'最後'條款,以便在發生異常時關閉它。 – 2016-11-30 15:02:43

2
public boolean isStreamClosed(FileOutputStream out){ 
    try { 
     FileChannel fc = out.getChannel(); 
     return fc.position() >= 0L; // This may throw a ClosedChannelException. 
    } catch (java.nio.channels.ClosedChannelException cce) { 
     return false; 
    } catch (IOException e) { 
    } 
    return true; 
} 

這僅適用於FileOutputStream!

-2

使用out.checkError()

while(!System.out.checkError()) { 
    System.out.println('hi'); 
} 

在這裏找到:How do I get java to exit when piped to head

+1

這可能適用於System.out ** PrintStream **,實際上它適用於任何PrintStream,但通常不適用於OutputStreams。 – IceArdor 2016-09-21 06:55:48