PrintStream API says:
All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.
This SO answer states:
If an OutputStream deals with bytes, what about
PrintStream.print(String)?
It converts chars to bytes using the default platform encoding. Using the default encoding is generally a bad thing** since it can lead to bugs when moving from one platform to another, especially if you are generating the file on one platform and consuming it on another.With a Writer, you typically specify the encoding to use, avoiding any platform dependencies.
Does't PrintStream(String fileName, String csn) use encoding to convert chars to bytes?
Why not use PrintStream constructors with encoding? We have same constructor API for PrintStream and PrintWriter! Why do we have this difference: "typically we don't provide encoding in PrintStream, and typically we do provide encoding in PrintWriter"?
1) But why we have encoding in PrintStream constructors?
PrintStream(File file, String csn)
PrintStream(String fileName, String csn)
PrintStream(OutputStream out, boolean autoFlush, String encoding)
If we use above constructors with encoding, does said in the beginning apply?
Besides, PrintWriter has exactly same constructors as PrintStream, so using PrintWriter(File file), PrintWriter(Writer out), PrintWriter(OutputStream out)
is no better than using PrintStream constructors without specifying encoding?
I don't understand why people say PrintStream is unsafe because it uses default encoding and PrintWriter is better. I think that both constructors of PrintStream and PrintWriter without encoding are bad, and both constructors of PrintStream and PrintWriter with encoding is fine.
As I understand, PrintStream may get char, char[], String to its print/println methods and then it needs to convert chars to byte to output them into FileOutputStream or some other OutputStream given to its constructor. For this PrintStream creates OutputStreamWriter internally and gives encoding to its constructor (if encoding was given to PrintStream constructor).