Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PrintStream to PrintWriter

Tags:

java

stream

Is there any possible way of converting PrintStream to PrintWriter (or vice versa) other than using WriterOutputStream which is in apache common?

like image 805
MBZ Avatar asked May 27 '12 05:05

MBZ


People also ask

What is the difference between PrintStream and PrintWriter?

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.

Is PrintWriter faster than PrintStream?

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.

What is PrintStream?

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

Is PrintStream buffered?

PrintStream is buffered, but flush does not degrade performance and BufferedOutputStream speeds up performance.


1 Answers

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.

like image 97
Eng.Fouad Avatar answered Oct 22 '22 22:10

Eng.Fouad