Navigation ( archives ›› 2006 ›› November ›› 30 ›› Convert a OutputStream to a JAVA String )

Convert a OutputStream to a JAVA String

Posted on November 30, 2006, 10:36 pm EST

The Problem

In one course of mine, I needed a way to pipe an Outstream to a String. I didn't find any solution online so a friend of mine (Sheldon) recommended me to do my own extended class to deal with it.

Update, simplest way

While catching the bus ride home, I figured out that we could of used ByteArrayOutputStream to feed into the OutputStream parameter and do a toString() right after. I believe the the same technique was used but I implemented it, which is kind of bad, since re-inventing the wheel is no good.

 // Instantiate the stream you want to use.
 ByteArrayOutputStream sos = new ByteArrayOutputStream();

 // To whatever you want with the stream.

 // Convert to String.
 String value = sos.toString();

I left the below content since it might be useful for some people to see how it was done.

Creating your own output stream

What I created was a class which extends the OutputStream, now we have to implement those methods, but keeping intact that we write to the StringBuffer instead to the stream. So here is how I did it:

 * Mohamed Mansour 
 * Created on November 29, 2006, 1:42 AM


 * @author Mohamed Mansour
public class StringOutputStream extends OutputStream {

	// This buffer will contain the stream
	protected StringBuffer buf = new StringBuffer();

	public StringOutputStream() {}

	public void close() {}

	public void flush() {

		// Clear the buffer
		buf.delete(0, buf.length());

	public void write(byte[] b) {
		String str = new String(b);
	public void write(byte[] b, int off, int len) {
		String str = new String(b, off, len);

	public void write(int b) {
		String str = Integer.toString(b);

	public String toString() {
		return buf.toString();

So as you seen, instead of placing some outputstream to the method you are choosing, you could place that class instead like the following.

StringOutputStream sos = new StringOutputStream();
someclass.somemethod(sos,"Some random method which needs an output stream");

See how nice that is? I used that class in my XML application. I had a library for XACML that allows the response to be encoded to some outputstream such as to disk, but I wanted to save it to some String object so I can process it. So by creating this class, it allowed me to do it efficiently.

I hope it will help some of you who need it.

Incase you would need to parse in a specific object, you could use the way I presented above, but if your just using it for a String object, I recommend you to use existing classes, since its already there.

About this Article:

Comments (2) - Add yours, or View the replies

Categoy (Software)

Views (54861)

Digg it: Digg this article