Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an OutputStream is closed

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?

like image 441
chrisbunney Avatar asked Dec 28 '11 12:12

chrisbunney


People also ask

How do you know if InputStream is closed?

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.

How do I close OutputStream?

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.

Do I need to close OutputStream?

Don't close the OutputStream of a ServletResponse. You should only close Streams you've opened.

What is difference between OutputStream and FileOutputStream?

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.


2 Answers

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.

like image 93
Peter Lawrey Avatar answered Oct 02 '22 11:10

Peter Lawrey


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; } 
like image 35
AlexR Avatar answered Oct 02 '22 11:10

AlexR