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.
views:
2168answers:
3
+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
2009-11-19 03:21:59
Wanna lowerCase that variable name `S` by any chance? You're hurting my eyes.
Asaph
2009-11-19 03:25:16
@Asaph - feel free to avert them :-)
ChssPly76
2009-11-19 03:26:26
@ChssPly76: +1 Thanks for changing it.
Asaph
2009-11-19 03:31:18
this is correct. thanks.
Rosarch
2009-11-19 03:45:10
+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
2009-11-19 03:23:05
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
2009-11-19 03:24:05