Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple and safe way to convert a PrintWriter into a PrintStream?

Is there a clean and simple way to convert an instance of java.io.PrintWriter into a java.io.PrintStream?

like image 818
Armand Avatar asked Nov 24 '10 15:11

Armand


People also ask

What is the difference between PrintWriter and 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.

Is PrintWriter faster than system out?

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.

How do I print from a PrintWriter?

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.

Is PrintWriter an output stream?

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.


1 Answers

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.

like image 148
Bozho Avatar answered Nov 15 '22 21:11

Bozho