The java documentation says to use Printwriter over Printstream when dealing with text, but why is this so? I know Printwriter deals with character streams and Printstream deals with byte streams but their both bytes at the end of the day. And since Java 1.5 PrintStream has not been limited to using the platform default encoding; there are constructors that accepts a charset name. So what benefit does Printwriter have over Printstream?
PrintStream
is ancient. Prefer PrintWriter
. Actually, it's better to use neither since both classes swallow exceptions silently.
I suggest using an OutputStreamWriter
wrapped by a BufferedWriter
.
PrintStream
cannot use a character encoding other than the default charset. If you need to write strings as UTF-8 bytes and the default JVM charset is Windows-1252 (as is the case when running Java on Windows), then PrintWriter
can do that, and PrintStream
cannot. That's the main difference, I think.
PrintWriter
doesn't allow you to write a byte[]
, while PrintStream
does. Allowing direct writing of byte[]
opens up the possibility of making mistakes by mixing character encodings which shouldn't be mixed.
PrintWriter
allows you to write a char[]
directly while PrintStream
does not.
PrintWriter
allows you to write a slice of a String without allocating a new String.