Java Reference
In-Depth Information
You set the input for the decompressor, which is the compressed data in a byte array.
byte[] input = get the compressed data in the byte array;
decompressor.setInput(input);
You call the inflate() method to decompress the input data. It accepts a byte array as its argument. It fills the
byte array with the decompressed data and returns the number of bytes in the byte array. After every call to this
method, you need to call the finished() method to check if the compression process is over. Typically, you use a
loop, as follows:
// Try to read the decompressed data 1024 bytes at a time
byte[] readBuffer = new byte[1024];
int readCount = 0;
while(!decompressor.finished()){
readCount = decompressor.inflate(readBuffer);
/* At this point, the readBuffer array has the decompressed
data from index 0 to readCount - 1.
*/
}
You need to call the end() method to release any resources held by the Inflater object.
// Indicates that the decompression process is over
decompressor.end();
Listing 9-2 illustrates how to use the Deflater and Inflater classes. The compress() and decompress() methods
accept the inputs and return the compressed and decompressed data, respectively. In this example, I have tried to
compress a small string of Hello world! . It is 12 bytes in length. It became 20 bytes after I compressed it. The goal of
compression is to reduce, not to increase, the size of data. However, you cannot achieve reducing the data size just
because you have attempted to compress it. The output of the program in Listing 9-2 is one such example. When you
compress the data, the compressed format has to add some information to it to do some housekeeping. If the data
you are attempting to compress is very small in size, as was the case in my example, or if it is already compressed, the
compressed size of the data may increase because of additional information added by the compression process.
Listing 9-2. Compressing and Decompressing a byte Array Using Deflater and the Inflater classes
// DeflateInflateTest.java
package com.jdojo.archives;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class DeflateInflateTest {
public static void main(String[] args) throws Exception {
String input = "Hello world!";
byte[] uncompressedData = input.getBytes("UTF-8");
 
Search WWH ::




Custom Search