Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to close an OutputStream in Java? [duplicate]

Tags:

This almost seems silly but what is the most reliable pattern to follow when closing an OutputStream? Right now I have something like the following which just seem to be try-catch-finally-overkill:

private void writeContentsToFile(OutputStream ostream, Properties contents) {     try {         contents.store(ostream, "comments");     }     catch (IOException e) {         throw new ResourceException("Failed to write contents", e);     }     finally {         try {             ostream.close();         }         catch (IOException e) { /* what can be done here anyway? */ }     } } 

Why close throws a checked exception is still a mystery to me. I can create wrapper method that does the close/catch block but if there is something already out there like FileUtil.closeFileAndThrowUncheckedException() I would like to use it. This gets a bit more useful when you have lots of smaller projects with lots of devs; one way to do it right.

like image 480
Andrew White Avatar asked Jun 07 '11 17:06

Andrew White


People also ask

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. The close method of OutputStream does nothing.

Do I need to close OutputStream?

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

Do we need to close Outputstreamwriter?

No, the topmost level Stream or reader will ensure that all underlying streams / readers are closed.

Which method is used to close a stream in java?

Calling close() will ensure that any remaining data is flushed as well as closing the OutputStream . close() statements typically appear in finally blocks.


1 Answers

If you are using Apache Commons, then IOUtils.closeQuietly() does the job nicely. See http://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.OutputStream)

like image 67
Sripathi Krishnan Avatar answered Sep 30 '22 07:09

Sripathi Krishnan