Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.
like image 877
Carlo Luther Avatar asked Jul 05 '13 18:07

Carlo Luther


People also ask

What is the use of FilterInputStream in Java?

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.

What is data input stream in Java?

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream. DataInputStream is not necessarily safe for multithreaded access.

Which are subclasses of FilterInputStream and FilterOutputStream?

Most filter streams provided by the java.io package are subclasses of FilterInputStream and FilterOutputStream and are listed here: DataInputStream and DataOutputStream. BufferedInputStream and BufferedOutputStream. LineNumberInputStream.

What is FilterOutputStream in Java?

io. FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams.


1 Answers

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.

like image 105
erickson Avatar answered Oct 20 '22 23:10

erickson