he classes in the java.io and java.nio packages make it easy to read and write just about any kind of datasuch as bytes, or arrays of bytes. Other classes make it easy to read and write other data types; however, all these classes read and write data in pieces that are at least a byte long. For example, the DataInputStream and DataOutputStream classes can write Boolean values, which requirein theoryonly a single bit to store. These classes, however, use an entire byte for each Boolean value.
In contrast, this article describes a pair of stream classes that let you read and write single bits easily. Not a bit stored as a byte, but a real bit. They treat the data stream as a stream of bits, rather than a stream of bytes. You don't have to think in terms of bytes at all.
This kind of facility is particularly useful when you are trying to save space. Some file formats store certain values using bit-lengths other than 8, 16, or 32. Otherssuch as data compression formatsbenefit from being able to forget about byte boundaries entirely, and to treat data as a homogenous stream of bits.
How BitInputStream and BitOutputStream Work
Before getting into the nitty-gritty, here's a quick glance at how you might use these classes. In many ways, they're like regular InputStream and OutputStream classes, except that they act on bits rather than bytes. Here's a program fragment that writes three bits1, 1, and 0to a file.
FileOutputStream fout =
new FileOutputStream( "bits.dat" );
BitOutputStream bout = new BitOutputStream( fout );
bout.writeBit( 1 );
bout.writeBit( 1 );
bout.writeBit( 0 );
bout.close();
Likewise, here's some code to read them back in:
FileInputStream fin = new FileInputStream( "bits.dat" );
BitInputStream bin = new BitInputStream( fin );
int b0 = bin.readBit();
int b1 = bin.readBit();
int b2 = bin.readBit();
bin.close();
Before learning how they work, you should think a little bit about how bits are stored in files.
|