Java.Servlet.What is the difference between PrintWriter and ServletOutputStream?

Both are used to send data from your servlet back to the client as part of the HTTP response.

But they are a little different:

FeaturePrintWriterServletOutputStream
Data typeCharacter stream (text data)Byte stream (binary data)
Best forWriting textual content (HTML, JSON, plain text)Writing binary content (images, PDFs, videos, file downloads)
Returned byresponse.getWriter()response.getOutputStream()
Encoding controlAutomatically handles encoding (e.g., UTF-8)You manually control bytes
Ease of useEasier for textNeeded for non-text (images, files)

🎯 In simpler words:

  • PrintWriter:
    • Works with characters (strings, text).
    • Buffered, convenient for writing HTML, JSON, plain text.
  • ServletOutputStream:
    • Works with raw bytes (binary).
    • Needed when you send binary data like files, images, etc.

🛠️ Tiny Example:

✅ Using PrintWriter for text:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<h1>Hello, World!</h1>");
}

✅ Using ServletOutputStream for binary data:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    ServletOutputStream out = response.getOutputStream();
    byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in bytes
    out.write(data);
}

⚡ Important Rule:

You can’t use both getWriter() and getOutputStream() in the same response!

  • If you call response.getWriter(), you cannot later call response.getOutputStream().
  • And vice versa.
  • Doing so causes IllegalStateException.

Because:

  • Writer and OutputStream are two different ways to manage the response body, and mixing them would break the HTTP response format.

🔥 Quick Practical Tip:

You want to send…Use…
HTML pagePrintWriter
JSON responsePrintWriter
Text file (plain text)PrintWriter
Image (PNG, JPEG)ServletOutputStream
PDF documentServletOutputStream
Zip file downloadServletOutputStream

🚀 Bonus Tip:

If you use PrintWriter, you should always set the character encoding early, for example:

response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

Otherwise the server default encoding (ISO-8859-1) might be used, causing weird text problems.

🛠️ Quick Summary Table:

AspectPrintWriterServletOutputStream
TypeText / Character streamBinary / Byte stream
Use forHTML, JSON, plain textImages, files, binary blobs
Methodresponse.getWriter()response.getOutputStream()
Can mix them?❌ No❌ No
This entry was posted in Без рубрики. Bookmark the permalink.