Filter Streams   «Prev  Next»

Lesson 4Chaining streams
ObjectiveExplore how to connect streams.

Chaining Java Streams(How to Connect?)

Data streams read and write strings, integers, floating-point numbers, and other data that is commonly presented at a higher level than mere bytes.
The java.io.DataInputStream and java.io.DataOutputStream classes read and write the primitive Java data types (boolean, int, double, etc.) and strings in a particular, well-defined, platform-independent format. Since DataInputStream and DataOutputStream use the same formats, they are complementary. What a data output stream writes, a data input stream can read. These classes are especially useful when you need to move data between platforms that may use different native formats for integers or floating-point numbers.

Data Stream Classes

The java.io.DataInputStream and java.io.DataOutputStream classes are subclasses of FilterInputStream and FilterOutputStream , respectively.
public class DataInputStream extends FilterInputStream implements DataInput
public class DataOutputStream extends FilterOutputStream
implements DataOutput

They have all the usual methods you have come to associate with input and output stream classes, such as read(), write(), flush(), available(), skip(), close(), markSupported(), and reset(). Data input streams support marking if, and only if, their underlying input stream supports marking. However, the real purpose of DataInputStream and DataOutputStream is not to read and write raw bytes using the standard input and output stream methods. It is to read and interpret multibyte data like ints, floats, doubles, and chars.

Java7 NIO 2

Chaining Streams

Every filter stream has an underlying stream that supplies the actual bytes of data. You specify the underlying stream that supplies the data in the filter stream's constructor. To create a new DataOutputStream connected to a FileOutputStream you might do this:

FileOutputStream fos = new FileOutputStream("ln.txt");
DataOutputStream lnos = new DataOutputStream(fos);

It is not uncommon to combine these into one line like this:
DataOutputStream lnos = new DataOutputStream(new FileOutputStream("ln.txt"));

You can chain multiple filters in sequence as shown in the following code:
FileInputStream fis = new FileInputStream("data.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);

Now the data input stream dis performs buffered reads from the file data.txt.