Wednesday 1 July 2015

Filter Streams

Filter Input Stream




Filter Output Stream,



What is the job of filter streams ?

The job of high-level streams is to add extra functionality to the existing streams.
For example, LineNumberInputStream adds line numbers in the destination file that do not exist in the source file.

DataInputStream increases performance with its readInt() and readLine() methods etc.

For higher functionality, one stream can be linked or chained to another, but obeying some simple rules. Chaining is very simple. The output of one stream becomes input to the other. Or to say, we pass an object of one stream as parameter to another stream constructor; this is how chaining is affected.

1. DataInputStream and DataOutputStream

DataInputStream and DataOutputStream are high-level as they are the sub classes of FilterInputStream and FilterOutputStream.

These streams' extra functionality is that they can read or write integers, doubles and lines at a time, instead of byte by byte.

This increases the performance to some extent; instead of reading and writing byte by byte with FileInputStream and FileOutputStream.

2. Giving Line Numbers – LineNumberInputStream

LineNumberInputStream is a subclass of FilterInputStream stream. We know each filter stream adds some extra functionality.

The LineNumberInputStream does the extra work of adding line numbers that do not exist in the source.

3. Using Buffering to Enhance the Performance

Buffering of streams increases the performance to higher extents of few thousand times.

For buffering, two streams exist in java.io package in byte streams category – BufferedInputStream and BufferedOutputStream. 

These high-level classes are sub classes of FilterInputStream and FilterOutputStream and their functionality is to increase the performance with buffer.

These streams give an implicit system-defined buffer (generally, 2048 bytes) into which data is read and written.

The buffer decreases the number of transfers between source file context area and destination file context area and thereby performance increases.

4. PushbackInputStream – Pushing unwanted extra character

Java permits to unread the unwanted bytes in a stream with the class PushbackInputStream.

This is an unusual filter stream and it pushes back a character into the input stream.

It is used to check a sequence of characters that meets with a condition or not.

It can check the delimiter of a line like \r (carriage-return) or \n (life-feed) etc.

If the sequence is broken out, it uses unread() method to push a byte back to the stream. Internally, the DataInputStream uses a PushbackInputStream to check for a line-feed (\n) sequence is crossed or not. For a program, you can go through PushbackReader.








No comments:

Post a Comment