Nick Heiner Nick Heiner - 1 year ago 1447
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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download