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?
For writing byte-oriented informations (such as image etc), we use ServletOutputStream class. It is a byte-stream class. On the other hand, PrintWriter class can only be used to write character based informations.
Whats the difference? OutputStreams are meant for binary data. Writers (including PrintWriter) are meant for text 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.
If strings are to be written to an OutputStream with a specific charset, PrintStream is the right choice. The reason for this is that PrintStream provides a constructor that accepts an OutputStream and an encoding. The PrintWriter constructor only counts an encoding if a file or a path is specified.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With