Java Reference
In-Depth Information
Adler32 and CRC32 checksums for HELLO
Adler32: 72089973
CRC32: 3242484790
Adler32 is faster than CRC32 . However, CRC32 gives a more robust checksum. Checksum is frequently used to
check for data corruption. CheckedInputStream and CheckedOutputStream are two concrete decorator classes in the
InputStream/OutputStream class family. They are in the java.util.zip package. They work with a Checksum object.
Note that Checksum is an interface, and the Adler32 and CRC32 classes implement the interface. CheckedInputStream
computes a checksum as you read data from a stream and CheckedOutputStream computes the checksum as you
write data to a stream. The ZipEntry class lets you compute the CRC32 checksum for an entry in a ZIP file using its
getCrc() method.
Compressing Byte Arrays
You can use the Deflater and Inflater classes in the java.util.zip package to compress and decompress data
in a byte array, respectively. These classes are the basic building blocks for compression and decompression in
Java. You may not use them directly very often. You have other high-level, easy-to-use classes in Java to deal with
data compression. Those classes are DeflaterInputStream , DeflaterOutputStream , GZIPInputStream , ZipFile ,
GZIPOutputStream , ZipInputStream , and ZipOutputStream . I will discuss these classes in detail in subsequent sections.
Using the Deflater and Inflater classes is not straightforward. You need to use the following steps to compress
data in a byte array.
1. Create a Deflater object.
2. Set the input data to be compressed using the setInput() method.
3. Call the finish() method indicating that you have supplied all input data.
4. Call the deflate() method to compress the input data.
5. Call the end() method to end the compression process.
You can create an object of the Deflater class using one of its constructors.
// Uses the no-args constructor
Deflater compressor = new Deflater();
Other constructors of the Deflater class let you specify the level of compression. You can specify the
compression level using one of the constants in the Deflater class. Those constant are BEST_COMPRESSION , BEST_
SPEED , DEFAULT_COMPRESSION , and NO_COMPRESSION . There is a trade-off in choosing between the best compression
and the best speed. The best speed means lower compression ratio and the best compression means slower
compression speed.
// Uses the best compression
Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION);
By default, the compressed data using the Deflater object will be in the ZLIB format. If you want the compressed
data to be in GZIP or PKZIP format, you need to specify that by using the boolean flag as true in the constructor.
// Uses the best speed compression and GZIP format
Deflater compressor = new Deflater(Deflater.BEST_SPEED, true);
You can supply the input data to the Deflater object in a byte array.
 
Search WWH ::




Custom Search