Response outputstream content length?

Trick picture Trick · Nov 18, 2009 · Viewed 18.5k times · Source

I am writing to output stream through various methods. How can I, before I close it, find out content length of the outputstream?

Answer

Jon Skeet picture Jon Skeet · Nov 18, 2009

The easiest way is probably to wrap it in another OutputStream implementation which forwards on all the write requests, but keeps an internal counter. Then you just write to that instead. Shouldn't be too hard to implement - and indeed there may be one already.

EDIT: Just guessing at a sensible name (CountingOutputStream) came up with an implementation in Apache Commons IO.

EDIT: As noted elsewhere, if this is for HTTP and your client isn't already doing buffering of the full data (in which case I'd have thought it could work out the content length), you may have problems due to needing to write the length before writing the data. In some cases you may find that it will work up to a certain size (which the client buffers) and then fail. In that case, David's solutions will be appropriate.