Convert OutputStream into an InputStream (Java 6 examples)

InputStreamFromOutputStream

This is how to use the class if you're using java 6 or lower, or you're not familiar with the "try with resources syntax":

final String dataId=//id of some data.
final InputStreamFromOutputStream<String> isOs = new InputStreamFromOutputStream<String>() {
   @Override
   public String produce(final OutputStream dataSink) throws Exception {
      /*
       * call the function who produces the data (writes to the OutputStream)
       * WARNING: we're in another thread here, so this method shouldn't 
       * write any class field or make assumptions on the state of the class. 
       */
      return produceMydata(dataId, dataSink)
   }
 };
 try {
  //here you can read from the InputStream the data that was previously written to the 
  //dataSink OutputStream (the usage of org.apache.commons.io.IOUtils is merely an example)
  byte[] read=IOUtils.toByteArray( isOs );
  //Use data here
 } catch (final IOException e) {
  //Handle exception here
 } finally {
  isOs.close();
 }
  //Optional: you can get the return value of produceMyData after the 
  //InputStream has been closed.
  String resultOfProduction = isOs.getResult();
}

Some programmers might be unfamiliar with the syntax of this example. It isOs is an anonymous inner class that overrides the method produce(OutputStream). You can still use standard inheritance if you prefer.

OutputStreamToInputStream

Same as above for OutputStreamToInputStream:

final OutputStreamToInputStream<String> oStream2IStream = new OutputStreamToInputStream<String>() {
    @Override
    protected String doRead(final InputStream istream) throws Exception {
         / *
           * Read the data from the InputStream "istream" passed as parameter. 
           * The data you read here is the one that will be written later in 
           * "oStream2IStream.write()". In this case it is the string "test". 
           * You should implement your own processing function (the usage of 
           * org.apache.commons.io.IOUtils here is merely an example).
           */
           final String result = IOUtils.toString(istream);
           // after the data has been processed you may optionally want to return a result.
           // this can be used in the method "getResult()". The following code is an example too.
           return result + " was processed.";
        }
    };

try {   
     /*
     * put here the code that writes to the OutputStream, the data will be 
     * passed to the method doRead(InputStream i) above.
     */
     oStream2IStream.write("test".getBytes());
} finally {
     // don't miss the close (or a thread would not terminate correctly).
     oStream2IStream.close();
}
//Optional: get the object returned by the method "doRead()" if necessary.
String result = oStream2IStream.getResult();
//result now contains the string "test was processed."

Reference guide Reference guide