ByteArrayOutputStream to PrintWriter (Java Servlet)

Thomas picture Thomas · Apr 26, 2010 · Viewed 10.1k times · Source

Writing generated PDF (ByteArrayOutputStream) in a Servlet to PrintWriter.

I am desperately looking for a way to write a generated PDF file to the response PrintWriter. Since a Filter up the hierarchy chain has already called response.getWriter() I can't get response.getOutputStream().

I do have a ByteArrayOutputStream where I generated the PDF into. Now all I need is a way to output the content of this ByteArrayOutputStream to the PrintWriter. If anyone could give me a helping hand would be very much appreciated!

Answer

Jon Skeet picture Jon Skeet · Apr 26, 2010

If something else has already called getWriter, it may well have already written some text to the response. Besides, PrintWriter is for text - you want to send arbitrary binary data... getOutputStream is definitely the way forward, so I would try to find the filter which has called getWriter and fix that instead.