Java: PrintStream to String?

java, printstream, string

Solution

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

Problem

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.

Original source