2

I think this has been answered but I can't seem to find it.

I have an instance method which writes some contents to an output stream

writeTo(OutputStream){
     //class specific logic
}

I want it to get these contents into a StringBuilder. I can do this via a temporary file but that does not seem right. I want to do something like:

Stringbuilder sb = /* */;
OutputStream os = outForStringBuilder(sb);//not sure how to do this
instance.writeTo(os); //This should write the contents to Stringbuilder
rocketboy
  • 9,573
  • 2
  • 34
  • 36

2 Answers2

13

Use a ByteArrayOutputStream and then call toString(charSet) - no need for a StringBuilder.

Tom
  • 43,583
  • 4
  • 41
  • 61
2

So you are wanting output written to the stream to go to a StringBuffer instead. I am assuming you are doing this because an OutputStream is required somewhere else. You could use ByteArrayOutputStream, but if you want to preserve the StringBuffer behavior, you might simply wrap a StringBuffer in a subclass of OutputStream like the code here:

http://geronimo.apache.org/maven/specs/geronimo-javamail_1.4_spec/1.6/apidocs/src-html/org/apache/geronimo/mail/util/StringBufferOutputStream.html#line.31

Centijo
  • 584
  • 6
  • 15