Java: PrintStream to String?

JavaStringPrintstream

Java Problem Overview


I have a function that takes an object of a certain type, and a PrintStream to which to print, and outputs a representation of that object. How can I capture this function's output in a String? Specifically, I want to use it as in a toString method.

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

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");

Solution 3 - Java

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();

Solution 4 - Java

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();

Solution 5 - Java

Maybe this question might help you: https://stackoverflow.com/questions/216894/get-an-outputstream-into-a-string

Subclass OutputStream and wrap it in PrintStream

Solution 6 - Java

Define and initialize a Scanner variable named inSS that creates an input string stream using the String variable myStrLine.

Ans: Scanner inSS = new Scanner(myStrLine);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick HeinerView Question on Stackoverflow
Solution 1 - JavaChssPly76View Answer on Stackoverflow
Solution 2 - JavaAsaphView Answer on Stackoverflow
Solution 3 - JavaClebert SuconicView Answer on Stackoverflow
Solution 4 - JavaKaelan DawnstarView Answer on Stackoverflow
Solution 5 - JavaKamil SzotView Answer on Stackoverflow
Solution 6 - Javauser7805633View Answer on Stackoverflow