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?
There's no API for determining whether a stream has been closed. Applications should be (and generally are) designed so it isn't necessary to track the state of a stream explicitly. Streams should be opened and reliably closed in an ARM block, and inside the block, it should be safe to assume that the stream is open.
close() method closes this output stream and releases any system resources associated with this stream. The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.
Don't close the OutputStream of a ServletResponse. You should only close Streams you've opened.
Outputstream is an abstract class whereas FileOutputStream is the child class. It's possible that you could use Outputstream to just write in bytes for a prexisting file instead of outputting a file.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With