Compressing and Uncompressing File Example in Java

Compressing and Uncompressing of the files is one of the common utility we use in our daily life. If you are using windows, using WinZip is very common to compress the files and sent to others. The advantage of compressing the files is to save the memory occupied for the file in the disk. It can be Uncompressed when it is really meeded.In Java IO package, the DeflaterOutputStream and InflaterInputStream classes provide mechanism to compress and uncompress the data in the deflate compression format.

Look at the below example to Compress and Uncompress a file.

Compressing and Uncompressing File Example

CompressFileExample.java

package javabeat.net.core;

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

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

		try {
			FileInputStream fin = new FileInputStream("TextFile.txt");

			FileOutputStream fout = new FileOutputStream("Compressed");
			DeflaterOutputStream out = new DeflaterOutputStream(fout);

			int i;
			while ((i = fin.read()) != -1) {
				out.write((byte) i);
				out.flush();
			}
			System.out.println("File is compressed!!");
			fin.close();
			out.close();

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

UncompressFileExample.java

package javabeat.net.core;

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

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

		try {
			FileInputStream fin = new FileInputStream("Compressed");
			InflaterInputStream in = new InflaterInputStream(fin);

			FileOutputStream fout = new FileOutputStream("UnCompressed.txt");

			int i;
			while ((i = in.read()) != -1) {
				fout.write((byte) i);
				fout.flush();
			}
			System.out.println("File is Uncompressed!!");
			fin.close();
			fout.close();
			in.close();

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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*