Share on Google+Share on Google+

Decompress file using Inflater class.

Advertisement
In this tutorial we will discuss about decompression of a file using Inflater class.

Decompress file using Inflater class.

In this tutorial, we will define the use of Inflater class. The Inflater class provide support for Decompression using ZLIB library.  The Inflater class is available in java.util.zip package.The read(....) method read uncompressed data in a bytes array.
            In the given Example, we will explain how to decompress file using Inflater class. The Inflater class create a decompresser. The FileInputStream class creates a input stream and read  bytes from file. The InflaterInputStream class creates a input stream with a given Inflater. It reads data from stream and decompress. The read() method of InflaterInputStream class read uncompressed  data into array of bytes.

About  Inflater API:

The java.util.zip.InflaterInputStream class extends java.util.zip.FilterOutputStream class. It provid following method:

Return Type Method Description 
int read() The read(....) method read uncompressed data in a bytes array.
void close() The close() method close input stream and releases system resources. 

Code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import java.io.IOException;

class Demo {
  public static String infile = "bharat.txt.dfl";

  public static String outfilename = "zip.txt";

  public static void dcompressFile() throws IOException {
    System.out.println("Compressed file : " + infile);
    System.out.println("Dcompressed file : " + outfilename);
    InflaterInputStream inflInstream = new InflaterInputStream(
        new FileInputStream(infile)new Inflater());
    FileOutputStream outstream = new FileOutputStream(outfilename);
    boolean completed = false;
    try {

      byte b[] new byte[1024];
      while (true) {
        int l = inflInstream.read(b, 01024);
        if (l == -1) {
          break;
        }
        outstream.write(b, 0, l);
      }
      completed = true;
      inflInstream.close();
      outstream.close();
    catch (IOException e) {
      System.out.println("hello");
    }
  }
}

public class InflaterDemo {
  public static void main(String[] argsthrows IOException {
    Demo.dcompressFile();
  }
}

Following is the output if you run the application:

C:\>java InflaterDemo
Compressed file : bharat.txt.dfl
Dcompressed file : zip.txt

Download this code

Advertisements

Advertisement

Posted on: July 16, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.