Java: FilterInputStream what are the advantages and use compared to other streams

inputstream, java, outputstream, stream

Solution

`FilterInputStream` is an example of the the Decorator pattern.

This class must be extended, since its constructor is `protected`. The derived class would add additional capabilities, but still expose the basic interface of an `InputStream`.

For example, a `BufferedInputStream` provides buffering of an underlying input stream to make reading data faster, and a `DigestInputStream` computes a cryptographic hash of data as it's consumed.

You would use this to add functionality to existing code that depends on the `InputStream` or `OutputStream` API. For example, suppose that you use some library that saves data to an `OutputStream`. The data are growing too large, so you want to add compression. Instead of modifying the data persistence library, you can modify your application so that it "decorates" the stream that it currently creates with a `ZipOutputStream`. The library will use the stream just as it used the old version that lacked compression.

Problem

I’ve been reading on InputStream, FileInputStream, ByteArrayInputStream and how their use seems quite clear (output streams too). What I’m struggling is to understand the use of FilterInputStream & FilterOutputStream: - What is the advantage of using it compared to the other stream classes? - When should I use it? - Please provide a theoretical explanation and a basic example.

Original source