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. 回答1: Use a ByteArrayOutputStream as a buffer: import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (PrintStream ps = new