How to Compress and Uncompress file in Java

A file or folder can be compressed in Java using any of the following classes

  1. DeflaterOutputStream
  2. GZIPOutputStream
  3. ZipOutputStream


Above classes are in the package java.util.zip. Also note that GZIPOutputStream and ZipOutputStream classes are derived from DeflaterOutputStream. Any one of them can be used to compress file or folder, they just differ in compress format.

Below is simple program to compress a file, using DeflaterOutputStream.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.DeflaterOutputStream;

public class CompressFile {
public static void main(String args[]){
	try {
FileOutputStream fos = new FileOutputStream("compressed.zip");
//assuming that abcd.txt file is in execution path of program
	FileInputStream fis = new FileInputStream("abcd.txt");

	DeflaterOutputStream dout = new DeflaterOutputStream(fos);
	int j;

	while((j=fis.read()) != -1)
        {
	dout.write((byte)j);

	dout.flush();
	}

	fis.close();
	fos.close();

}catch(Exception e){
System.out.println(e);
r.printStackTrace();
}
System.out.println("Done");
}
}


A compressed file or folder, can be uncompressed using any of below classes

  1. InflaterInputStream
  2. GZIPInputStream
  3. ZipInputStream

Above classes are in the package java.util.zip. Also note that GZIPInputStream and ZipInputStream classes are derived from InflaterInputStream.

Below is simple program to uncompress a file, using InflaterInputStream

import java.io.*;
import java.util.zip.InflaterInputStream;

class UnCompressFile{
public static void main(String args[]){

try{
FileOutputStream fos=new FileOutputStream("abcd.txt");

FileInputStream fis=new FileInputStream("compress.zip");
InflaterInputStream inf=new InflaterInputStream(fis);

int k;

while((k=inf.read())!=-1)
{
fos.write((byte)k);
fos.flush();
}

fis.close();
fos.close();
inf.close();

}catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
System.out.println("Done");
}
}

You may also like to read:
How to take input from Standard input
SequenceInputStream example
FileWriter and FileReader example

One thought on “How to Compress and Uncompress file in Java”

Leave a Reply