How to convert String to OutputStream?

A method needs a parameter OutputStream to write result data (text) to. It works fine when I set new FileOutputStream(myFile) as the parameter value. But how can I set an OutputStream that is not a file (but in memory). E.g. I would like to set a StringBuilder/StringBuffer as the parameter instead of the OutputStream. Is there a way to "wrap" a StringBuilder/StringBuffer/STring into an OutputStream?

[409 byte] By [MartinHilperta] at [2007-11-27 10:23:28]
# 1

Hi Martin,

note that an OutputStream receives bytes, not characters. So it is possibly not a good idea to put the content in a String. A byte array would fit better. And voila .. there is a java.io.ByteArrayOutputStream class, which exactly does that. At the end you can get the written data as an array of bytes. You can also get it as a String, provided you tell it the encoding to be used for converting bytes to chars.

martin@worka at 2007-7-28 17:22:06 > top of Java-index,Java Essentials,Java Programming...
# 2

Yup, ByteArrayOutputStream did the trick - thanks!

MartinHilperta at 2007-7-28 17:22:06 > top of Java-index,Java Essentials,Java Programming...