3

When adding to some content to HttpServletResponse in java I can either get the response writer and append:

httpResponse.getWriter().append("Some Content");

Or I can add content to the output-stream:

ServletOutputStream servletOut = httpResponse.getOutputStream();
servletOut.write(someByteArray);

Is the only difference between the two is that the first gets strings/char-sequences and the second gets bytes (of course the content-type is affected as well)? Should I prefer one over the other? When should I use which?

Cœur
  • 37,241
  • 25
  • 195
  • 267
forhas
  • 11,551
  • 21
  • 77
  • 111
  • Please look at http://stackoverflow.com/questions/6883715/whats-the-difference-between-printwriter-and-outputstream – محمد Jun 08 '15 at 10:23

3 Answers3

3

Below table shows difference between them, You can use any of these based on requirement which fits in the table.

enter image description here

Vivek Gupta
  • 955
  • 4
  • 7
2

ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.

PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified then it does default character encoding.

underdog
  • 4,447
  • 9
  • 44
  • 89
2

Actually.. byte streams will be significant compared to character streams only in the case of internationalization.

The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.

For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and output done with stream classes automatically translates to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.

If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. Later, if internationalization becomes a priority, your program can be adapted without extensive recoding.

Hope this answers your question...

Pavan Kumar K
  • 1,360
  • 9
  • 11