Java Reference
In-Depth Information
In addition to the standard I/O classes, our program consists of several
additional classes. Because we need to perform bit-at-a-time I/O, we write
wrapper classes representing bit-input and bit-output streams. We write other
classes to maintain character counts and create and return information about a
Huffman coding tree. Finally, we write compression and uncompression
stream wrappers. To summarize, the classes that we write are
BitInputStream
Wraps an
Inputstream
and provides bit-at-a-time input.
BitOutputStream
Wraps an
Outputstream
and provides bit-at-a-time
output.
CharCounter
Maintains character counts.
HuffmanTree
Manipulates Huffman coding trees.
HZIPInputStream
Contains an uncompression wrapper.
HZIPOutputStream
Contains a compression wrapper.
bit-input and bit-output stream classes
The
BitInputStream
and
BitOutputStream
classes are similar and are shown in
Figures 12.14 and 12.15, respectively. Both work by wrapping a stream. A
reference to the stream is stored as a private data member. Every eighth
readBit
of the
BitInputStream
(or
writeBit
of the
BitOutputStream
classes)
causes a
byte
to be read (or written) on the underlying stream. The
byte
is
stored in a buffer, appropriately named
buffer
, and
bufferPos
provides an indi-
cation of how much of the buffer is unused.
The
getBit
and
setBit
methods are used to access an individual bit in
an 8-bit
byte
; they work by using bit operations. (Appendix C describes
the bit operators in more detail.) In
readBit
, we check at line 19 to find out
whether the bits in the buffer have already been used. If so, we get 8 more
bits at line 21 and reset the position indicator at line 24. Then we can call
getBit
at line 27.
The
BitOutputStream
class is similar to
BitInputStream
. One difference is
that we provide a
flush
method because there may be bits left in the buffer at
the end of a sequence of
writeBit
calls. The
flush
method is called when a call
to
writeBit
fills the buffer and also is called by
close
.
Neither class performs error checking; instead they propagate any
IOException
s. Thus full error checking is available.
Search WWH ::
Custom Search