Monday, January 4, 2010

Section 6.2. The Filter Stream Subclasses










6.2. The Filter Stream Subclasses










The java.io package contains many useful filter stream classes.
The BufferedInputStream and BufferedOutputStream classes buffer reads and writes by first putting data into a buffer (an internal array of bytes). Thus, an application can read or write bytes to the stream without necessarily calling the underlying native methods. 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. Buffered input streams also allow the reader to back up and reread data.


The java.io.PrintStream
class allows very simple printing of primitive values, objects, and string literals. It uses the platform's default character encoding to convert characters into bytes. This class traps all IOExceptions and is primarily intended for debugging. System.out and System.err are the most popular examples of the PrintStream class, but you can connect a PrintStream filter to other output streams as well. For example, you can chain a PrintStream to a FileOutputStream to write formatted strings into a file. These classes will be discussed in the next chapter.


The PushbackInputStream
class has a 1-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.


The ProgressMonitorInputStream class shows the user a running tally of how much data has been read and how much remains to be read.


The DataInputStream
and DataOutputStream
classes read and write primitive Java data types and strings in a machine-independent way. (Big-endian for integer types, IEEE-754 for floats and doubles, a variant of UTF-8 for strings.) These classes will be discussed in Chapter 8. The ObjectInputStream and ObjectOutputStream classes extend DataInputStream and DataOutputStream with methods to read and write arbitrary Java objects as well as primitive data types. These will be taken up in Chapter 13.


The java.util.zip package also includes several filter stream classes. The filter input streams in this package decompress compressed data; the filter output streams compress raw data. Because compressed files are particularly vulnerable to corruption, this package also provides filters that maintain a running checksum of the data in a file. These will be discussed in Chapter 10.


The java.util.security package contains the DigestInputStream and DigestOutputStream filter streams;
these calculate message digests of the data that passes through them. The Java Cryptography Extension (JCE) adds two more filter streams to this package, CipherInputStream and CipherOutputStream, which can encrypt or decrypt data using a variety of algorithms. These filter streams will be discussed in Chapter 12.












No comments: