Is there a clean and simple way to convert an instance of java.io.PrintWriter
into a java.io.PrintStream
?
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.
PrintWriter class is the implementation of Writer class. By using PrintWriter than using System. out. println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.
The print writer is linked with the file output.PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method.
Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
First obtain an OutputStream
from the Writer
. See this question
Then pass it as argument to the PrintStream
constructor:
OutputStream os = new WriterOutputStream(writer);
PrintStream ps = new PrintStream(os);
Update: commons-io 2.0 has WriterOutputStream
, so use it.
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