views:

2168

answers:

3

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.

+7  A: 

Use ByteArrayOutputStream as buffer:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
your_function(object, ps);
String content = baos.toString(charsetName); // e.g. ISO-8859-1
ChssPly76
Wanna lowerCase that variable name `S` by any chance? You're hurting my eyes.
Asaph
@Asaph - feel free to avert them :-)
ChssPly76
@ChssPly76: +1 Thanks for changing it.
Asaph
this is correct. thanks.
Rosarch
+4  A: 

You can construct a PrintStream with a ByteArrayOutputStream passed into the constructor which you can later use to grab the text written to the PrintStream.

ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
...
String output = os.toString("UTF8");
Asaph
A: 

Maybe this question might help you: http://stackoverflow.com/questions/216894/get-an-outputstream-into-a-string

Subclass OutputStream and wrap it in PrintStream

Kamil Szot