Mohamed Mansour's Personal Website
Articles
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.
CODE:
// Instantiate the stream you want to use.
ByteArrayOutputStream sos = new ByteArrayOutputStream();
// To whatever you want with the stream.
...
someclass.dowhatever(sos);
...
// 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 StringOutputStream.java 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:
CODE:
/*
* StringOutputStream.java
*
* Mohamed Mansour
* www.m0interactive.com
*
* Created on November 29, 2006, 1:42 AM
*/
import java.io.OutputStream;
/**
* @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);
this.buf.append(str);
}
public void write(byte[] b, int off, int len) {
String str = new String(b, off, len);
this.buf.append(str);
}
public void write(int b) {
String str = Integer.toString(b);
this.buf.append(str);
}
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.
CODE:
StringOutputStream sos = new StringOutputStream();
someclass.somemethod(sos,"Some random method which needs an output stream");
System.out.println(sos.toString());
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.

