Convert an OutputStream in an InputStream (or a Writer into a Reader)

If you are programming using java streams, sometimes you'll find yourself in a situation in which a method creates data and writes them into an OutputStream and you need to use them in another method that expects to read the data from an InputStream. Most of the times it happens when using poorly designed external libraries.

Basic Concepts

  • InputStream and Reader are two abstract classes that you use as a source of data. You use them when reading data from a file, a database a socket... The data is "coming in" your application to be processed.
Representation of an InputStream
  • OutputStream and Writer are two abstract classes that you use as a sink of data. You use them when writing data to a file a database, a socket... The data is "going out" your application after it has been processed.
Representation of an OutputStream

Next