Is there any possible way of converting PrintStream
to PrintWriter
(or vice versa) other than using WriterOutputStream
which is in apache common?
PrintStream and PrintWriter have nearly identical methods. The primary difference is that PrintStream writes raw bytes in the machine's native character format, and PrintWriter converts bytes to recognized encoding schemes.
PrintStreams can allow more flexibility with encoding. I'm guessing that some system encodings are used, but I'm not sure. PrintWriter is also about twice as fast for printing text.
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.
PrintStream is buffered, but flush does not degrade performance and BufferedOutputStream speeds up performance.
To convert PrintStream
to PrintWriter
, use the constructor: PrintWriter(OutputStream out)
With that constructor, you risk getting the incorrect encoding, since PrintStream
has an encoding but using PrintWriter(OutputStream out)
ignores that and just uses the system's default charset. If you don't want the system default, you will have to keep the encoding in a separate field or variable and use:
pw = new PrintWriter(new OutputStreamWriter(myPrintStream, encoding));
Where encoding
can be (for example) "UTF-8"
or an instance of Charset
.
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