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:
Feature | PrintWriter | ServletOutputStream |
---|---|---|
Data type | Character stream (text data) | Byte stream (binary data) |
Best for | Writing textual content (HTML, JSON, plain text) | Writing binary content (images, PDFs, videos, file downloads) |
Returned by | response.getWriter() | response.getOutputStream() |
Encoding control | Automatically handles encoding (e.g., UTF-8) | You manually control bytes |
Ease of use | Easier for text | Needed 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 callresponse.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 page | PrintWriter |
JSON response | PrintWriter |
Text file (plain text) | PrintWriter |
Image (PNG, JPEG) | ServletOutputStream |
PDF document | ServletOutputStream |
Zip file download | ServletOutputStream |
🚀 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:
Aspect | PrintWriter | ServletOutputStream |
---|---|---|
Type | Text / Character stream | Binary / Byte stream |
Use for | HTML, JSON, plain text | Images, files, binary blobs |
Method | response.getWriter() | response.getOutputStream() |
Can mix them? | ❌ No | ❌ No |