Tuesday 8 May 2012

The amazing ByteArrayOutputStream

The use of streams can boost
the performance of your application.

It is often the case that a method writes its output to an OutputStream, but, it happens that you simply want the output as a String. This is the case when you need to make use of the class ByteArrayOutputStream.

Here is a simple example assuming that the aforementioned method implements the prototype:

class IMyClass implements Closeable {
   void someMethod(OutputStream s);
}
Here is the example:
IMyClass xyz = ...; // Initialize your object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
someMethod(baos);
xyz.close(); // First close your object (it's closeable)
String your_result = baos.toString();
baos.close();

No comments:

Post a Comment