开发者

Servlets in java - both getWriter() and getOutputStream()

Why is it th开发者_JAVA技巧at on an instance of ServletResponse both getWriter() and getOutputStream() can't be called?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜