Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there anyway to check whether an OutputStream is closed without attempting to write to it and catching the IOException?

For example, consider the following contrived method:

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

What could you replace /* stream isn't closed */ with?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

The underlying stream may not know it its closed until you attempt to write to it (e.g. if the other end of a socket closes it)

The simplest approach is to use it and handle what happens if it closed then, rather than testing it first as well.

No matter what you test, there is always the chance you will get an IOException, so you cannot avoid the exception handling code. Adding this test is likely to complicate the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...