Share on Google+Share on Google+

How to Compress file using DeflaterOutputStram class in java.

In this tutorial you will see how to Compress file using DeflaterOutputStram class in java.

How to Compress file using DeflaterOutputStram class in java.

In this tutorial, we will discuss  how to use DeflaterOutputStream class in java. The DeflaterOutputStream class creates an output Stream for compressing data with an associated deflater. The DeflaterOutputStream class is available in package. The write(int b) method of DeflaterOutputStream class write one byte on associated stream.
    In this Example, we will compressed the data of a file by using DeflaterOutputStream class. The DeflaterOutputStream(OutStream out, Deflater defl) constructor  DeflaterOutputStream class create an output stream with a specific compressor.  The Defleter class create a compressor  for compressing data.  The FileInputStream class creates a input stream for reading data from a file. The setLevel() method of Deflater class is used to set level of data compression. The read() method of  FileInputStream class read data from input stream.

About DeflaterOutputStream API:

The class extends class. It provides the following methods:

Return Type Method Description 
int write(int b) The write( int b) method write one byte on associated output stream
void close() The close() method close underlaying output stream after writing compressed data.
void finish() The finish() method finish writing compressed data on associated stream without closing stream.



public class DeflOutStream {
  public static void main(String[] args) {
    String compressfile = "newfile.txt";
    try {
      FileInputStream finStream = new FileInputStream("testfile.txt");
      FileOutputStream foutStream = new FileOutputStream(compressfile);
      Deflater dfl = new Deflater();
      DeflaterOutputStream dflOutStream = new DeflaterOutputStream(
          foutStream, dfl);
      for (int d =; d != -1; d = {
      .println("Fill data SuccessFully Compressed at Level : 4");

    catch (IOException ioex) {
      System.err.println("IOException is :" + ioex);


Following is the output if you run the application:

C:\>java DeflOutStream
Fill data SuccessFully Compressed at Level : 4

Download this code


Posted on: July 19, 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.


Advertisement null