How to check whether an OutputStream is closed

41,733

Solution 1

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.

Solution 2

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;
}

Solution 3

The OutputStream itself does not support such a method. The Closable interface is defined in a way that once you call close() you are going to dispose of that OutputStream.

Maybe you should revisit a bit the design of the application and check why you're not doing that and you're ending up with a closed OutputStream instance still running around in your application.

Solution 4

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;
}

This is possible only for a FileOutputStream!

Solution 5

If you're doing this in tests, use mockito Spys, then do a verify

I had a test effectively

import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Test;
import java.io.InputStream;

class MyTest {
    @Test
    public void testInputStreamCloseCalled() throws IOException {
        final InputStream spied = spy(...)
    
        // Do something that should call .close() on the spied InputStream
        spied.close()

        verify(spied, times(1)).close();
    }
}

Where ... is the input stream you're acting upon.

Would work with OutputStreams too.

Share:
41,733
chrisbunney
Author by

chrisbunney

Java and Python developer. Interested in software project management, agile development, quality assurance, and writing damn good code.

Updated on August 21, 2020

Comments

  • chrisbunney
    chrisbunney over 3 years

    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?