Java Reference
In-Depth Information
about next, while others provide a new interface for using the streams,
such as the print streams. These classes are
Filter
streams because
they can form part of a filter chain.
Exercise 20.2
: Rewrite the
translateByte
class as a filter.
Exercise 20.3
: Create a pair of
Filter
stream classes that encrypt
bytes using any algorithm you choosesuch as
XOR
ing the bytes with some
valuewith your
DecryptInputStream
able to decrypt the bytes that your
En-
cryptOutputStream
class creates.
Exercise 20.4
: Create a subclass of
FilterReader
that will return one
line of input at a time via a method that blocks until a full line of input
is available.
20.5.3.
Buffered
Streams
The
Buffered
stream classes
BufferedInputStream
,
BufferedOutputStream
,
BufferedReader,
and
BufferedWriter
buffer their data to avoid every
read
or
write
going directly to the next stream. These classes are often used in
conjunction with
File
streamsaccessing a disk file is much slower than
using a memory buffer, and buffering helps reduce file accesses.
Each of the
Buffered
streams supports two constructors: One takes a
reference to the wrapped stream and the size of the buffer to use, while
the other only takes a reference to the wrapped stream and uses a de-
fault buffer size.
When
read
is invoked on an empty
Buffered
input stream, it invokes
read
on its source stream, fills the buffer with as much data as is available-
only blocking if it needs the data being waited forand returns the re-
quested data from that buffer. Future
read
invocations return data from
that buffer until its contents are exhausted, and that causes anoth-
er
read
on the source stream. This process continues until the source
stream is exhausted.