How to send data from OutputStream to a String in Java?

The solution is relatively simple but it got me a while until I’ve found a solution on the net.
You have to use a ByteArrayOutputStream, a constructor of String and know the character encoding used by the method which you get your OutputStream from.
A little code:
ByteArrayOutputStream os = new ByteArrayOutputStream();
String aString = new String(os.toByteArray(),"UTF-8");
And that’s all:) Pay attention to the character encoding.


  • can you please explain the code too. what is aClass

  • thanks man. you saved hours to find this simple answer!

Leave a Reply to saba Cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>