Nick Heiner Nick Heiner - 5 months ago 382
Java Question

Java: PrintStream to String?

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.

Answer

Use a ByteArrayOutputStream as a buffer:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
yourFunction(object, ps);
String content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
Comments