Piping Output Stream to an Input Stream

The Problem

Recently I had to write adapter for some API interface. Implementation was quite usual and the method of interest was void setValue(InputStream). Interface that I had to adapt exposed OutputStream write(), lucky me.

The Solution

First, exposing OutputStream is a bad idea. API client have to push data into the output stream and receiving side must consume bytes at the forced speed or provide potentially huge buffer not to block the client. The ideal solution would be to change the API to accept InputStream: such API requires minimum efforts from the client and allows implementation to extract data at appropriate rate.

So, what could I do to make it work now? Below is a simple solution that essentially collects all bytes in a buffer and then wraps it in input stream:

public OutputStream write() {
  return new ByteArrayOutputStream() {

    public void close() throws IOException {
      super.close();
      try {
        consumer.consume(new ByteArrayInputStream(buf, 0, count));
      } catch (ConsumerException ce) {
        throw new IOException(ce);
      }
    }

  };
}

You can download the complete sample here: iofun.zip.

  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • LinkedIn
  • E-mail this story to a friend!
  • Print this article!

blog comments powered by Disqus