17

First,we have PrintWriter

java.io.File f=new java.io.File("s.txt");

   java.io.PrintWriter out=new java.io.PrintWriter(f);

   out.print(5);

   out.print(7);

   out.close();

Then we have outputstream

 java.io.File f=new java.io.File("s.txt");

 java.io.FileOutputStream out=new java.io.FileOutputStream(f);

   out.write(5);

   out.write(7);

   out.close();

Whats the difference?

rena-c
  • 325
  • 2
  • 3
  • 12

2 Answers2

32

OutputStreams are meant for binary data. Writers (including PrintWriter) are meant for text data.

You may not see the difference in your specific situation as you're calling PrintWriter.write(int) which writes a single character - if the character encoding you're using just maps characters to the same byte, for characters less than 127, then you'll see the same result. But if you give it a different encoding, then you'll see a difference.

PrintWriter is also different in that it suppresses IO exceptions - as does PrintStream, which is the binary stream equivalent of PrintWriter.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

From this java2novice.com link I extracted the following, that is similar to what Jon said:

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.

Christian Vielma
  • 15,263
  • 12
  • 53
  • 60