Filter Streams   «Prev  Next»

Lesson 3The different filter streams
ObjectiveExamine the Purposes of the Filter Stream Classes.

Purpose of Java Filter Stream Classes

There are several stream classes in the java.io package that perform different kinds of filtering. You can also write your own classes to do custom filtering. Furthermore, you can chain multiple filters together to get the effect of a combined filter.

Buffered reads and writes

The BufferedInputStream and BufferedOutputStream classes buffer reads and writes by reading or writing data first into a buffer.
Thus an application can read or write bytes to the stream without necessarily calling the underlying native method. The data is read from or written into the buffer in blocks; subsequent accesses go straight to the buffer.
This improves performance in many situations. BufferedInputStream also allows the reader to back up and reread data that's already been read.

5.3 Filter Stream Classes

java.io.FilterInputStream and java.io.FilterOutputStream are concrete superclasses for input and output stream subclasses that somehow modify or manipulate data of an underlying stream:
public class FilterInputStream extends InputStream
public class FilterOutputStream extends OutputStream

Each of these classes has a single protected constructor that specifies the underlying stream from which the filter stream reads or writes data:
protected FilterInputStream(InputStream in)
protected FilterOutputStream(OutputStream out)
These constructors set protected InputStream and OutputStream fields, called in and out, inside the FilterInputStream and FilterOutputStream classes, respectively.
protected InputStream in
protected OutputStream out


Since the constructors are protected, filter streams may only be created by subclasses. Each subclass implements a particular filtering operation. Normally, such a pattern suggests that polymorphism is going to be used heavily, with subclasses standing in for the common superclass; however, it is uncommon to use filter streams polymorphically as instances of FilterInputStream or FilterOutputStream. Most of the time, references to a filter stream are either references to a more specific subclass like BufferedInputStream or they are polymorphic references to InputStream or OutputStream with no hint of the filter left.


Reading and writing data types

The DataInputStream and DataOutputStream classes read and write primitive Java data types and strings in a machine independent way.

PrintStream

Pushback

The PushbackInputStream class has a one-byte pushback buffer so a program can unread the last character read. The next time data is read from the stream, the unread character is reread.

Java7 NIO 2