How to check whether an OutputStream is closed

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.


Unfortunately OutputStream API does not have method like isClosed().

So, I know only one clear way: create your class StatusKnowingOutputStream that wraps any other output stream and implements its close() method as following:

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

Now add method isClosed()

public boolean isClosed() {
    return closed;
}