Nick Heiner Nick Heiner - 10 months ago 893
Java Question

Java: PrintStream to String?

I have a function that takes an object of a certain type, and a

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


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