Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: PrintStream to String?

People also ask

What does PrintStream mean in java?

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method.

What is PrintStream flush in java?

The flush() method of PrintStream Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream.

Can you print a string in java?

The println(String) method of PrintStream Class in Java is used to print the specified String on the stream and then break the line. This String is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be printed in the Stream.

Do I need to close PrintStream?

No. It is not require to close other components.


Use a ByteArrayOutputStream as a buffer:

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final String utf8 = StandardCharsets.UTF_8.name();
    try (PrintStream ps = new PrintStream(baos, true, utf8)) {
        yourFunction(object, ps);
    }
    String data = baos.toString(utf8);

You can construct a PrintStream with a ByteArrayOutputStream passed into the constructor which you can later use to grab the text written to the PrintStream.

ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
...
String output = os.toString("UTF8");

Why don't you use a StringWriter with a PrintWriter?

StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("Hello World!");
String output = writer.toString();

A unification of previous answers, this answer works with Java 1.7 and after. Also, I added code to close the Streams.

final Charset charset = StandardCharsets.UTF_8;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, charset.name());
yourFunction(object, ps);
String content = new String(baos.toByteArray(), charset);
ps.close();
baos.close();

Maybe this question might help you: Get an OutputStream into a String

Subclass OutputStream and wrap it in PrintStream