Why is it that on an instance of ServletResponse
both getWriter()
and getOutputStream()
can't be called?

- 124,154
- 35
- 280
- 359

- 9,148
- 17
- 50
- 69
-
It might help if you were to explain why you wanted to call both in one servlet request. – Jan 20 '11 at 10:49
-
It is probably not Abkutty wanting to call both, but the Servlet, the error handling Servlet, and some Filter all trying to write output, and not properly coordinating among themselves which method to use. – Thilo Jan 20 '11 at 10:52
-
I would think again about why you want to have both. – Peter Lawrey Jan 20 '11 at 10:55
-
1@Phil & @Peter: It was just a question on the design decision, not that I wanted to have both. – abson Jan 20 '11 at 11:10
3 Answers
A design decision. The Writer and the OutputStream both maintain their own buffer. If you created one each then their output would need to be merged somehow. Possible, but more complicated. So they decided that you have to choose if you want character-based output or binary output.

- 257,207
- 101
- 511
- 656
-
So why does not getWriter() returns a wrapper on getOutputStream()'s result? – Amir Pashazadeh Sep 14 '13 at 04:57
-
Because if you tried to write to both, you'd mess up the result due to uncoordinated buffering. Or are you asking why Writer does not expose OutputStream's binary output methods? – Thilo Sep 14 '13 at 05:02
Because a Writer
is a higher-level abstraction than OutputStream
. It controls the character encoding of the underlying stream, and incorporates its own buffering mechanisms.
If you were to write direct to the OutputStream after previously using the Writer, there would be a high risk of corruption of the underlying stream, either because of mixed-up character encoding, or missing buffered data.
To prevent this mix-up, the servlet API forbids using both for any one response.
More practically, you use OutputStream for writing binary content, and Writer for writing textual content.

- 398,947
- 96
- 818
- 769
Generally this is because getOutputStream()
is used to write binary content, whereas getWriter()
is used to write textual content. It wouldn't make sense to write both in one servlet request - you should either use one or the other.
-
Thanks! I was able to get rid of my error "getOutputStream() has already been called on this response" by eliminating the call getWriter() and using only getOutoutStream(). – monal86 Mar 23 '18 at 17:43