Alex Rivera | Logout

Does closing a BufferedOutputStream also close the underlying OutputStream?

Asked 2009-09-15T16:08:21.033
14

I am streaming binary data (a CSV file extracted from the database as a Clob) to the browser by calling response.getOutputStream() and would normally wrap the OutputStream in a BufferedOutputStream when copying the data.

Should I close the BufferedOutputStream or will this also close the underlying OutputStream?

[Extra question: Do I need to use a BufferedOutputStream in this case or is the response already buffered?]

Edit
Report

1 Answer

15

Yes, it closes it. As for whether you should close it - are you expecting to write anything else to the response stream? If not, I think it's fine to close it. If you don't close it, you should obviously flush it instead - but I suspect you could figure that bit out for yourself :)

The behaviour is actually inherited from FilterOutputStream. The Javadocs for for FilterOutputStream.close state:

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

As for whether you should buffer it - I'm not sure that this is well defined. It may be buried in the servlet spec somewhere - and it may even be configurable (sometimes you really don't want buffering, but if you can buffer the whole response it means you can serve a nicer error page if things go wrong after you've started writing).

answered 2009-09-15T16:10:13.447

Your Answer