Java Reference
In-Depth Information
Q: You mentioned the BufferedInputStream class that buffers the
data. What if I want to buffer the data read from the file?
A: That's a good idea. Reading one byte at a time from a file is terri-
bly inefficient, so I recommend buffering any time you can. You
can attach the high-level BufferedInputStream class to the FileIn-
putStream object, and the data will be buffered automatically.
Q: OK, but I want to read the data from the file using the buffer and
filter it using the DataInputStream class.
A: Then you use all three classes—one low-level stream and two
high-level streams. You start with a FileInputStream object that
reads from the file. Chain to that a BufferedInputStream object
that buffers the file input, and then chain to the buffer a DataIn-
putStream object that filters the data into primitive data types.
That's how the java.io classes are chained together to create the
exact type of input you want. Let me show you an example of
chaining streams.
Chaining Streams Together
The following ChainDemo example demonstrates the DataOutputStream
class, which contains methods such as:
public void writeDouble(double d)
■■
public void writeFloat(float f)
■■
public void writeInt(int x)
■■
public void writeLong(long x)
■■
public void writeShort(short s)
■■
public void writeUTF(String s)
■■
There are similar methods for writing bytes, chars, and booleans. Similarly,
the DataInputStream contains corresponding read() methods for reading in
these data types. In addition, the ChainDemo program buffers the output to
improve efficiency using the BufferedOutputStream class. The BufferedOut-
putStream class has two constructors:
public BufferedOutputStream(OutputStream source).
Buffers the out-
put to the specified stream using a 512-byte buffer.
public BufferedOutputStream(OutputStream source, int size). Buffers
the output to the specified stream using a buffer of the specified size.
Search WWH ::




Custom Search