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.
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.
Don't close the OutputStream of a ServletResponse. You should only close Streams you've opened.
No, the topmost level Stream or reader will ensure that all underlying streams / readers are closed.
Calling close() will ensure that any remaining data is flushed as well as closing the OutputStream . close() statements typically appear in finally blocks.
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)
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