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 f
A unification of previous answers, this answer works with Java 1.7 and after. Also, I added code to close the Streams.
final Charset charset = StandardCharsets.UTF_8;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, charset.name());
yourFunction(object, ps);
String content = new String(baos.toByteArray(), charset);
ps.close();
baos.close();