Java: PrintStream to String?

Nick Heiner picture Nick Heiner · Nov 19, 2009 · Viewed 84.6k times · Source

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

ChssPly76 picture ChssPly76 · Nov 19, 2009

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