Working with java.util.zip compression API

In this article I shall discuss about how to compress files using Java. Java has a package of classes that allow data compression.Let’s see how easy it is to compress all files in a folder.The first step is to import the classes that we will use:

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

Working with java.util.zip files

Package java.io classes will be used to manipulate streams input and output data.While the package java.util.zip are classes that will make the compression of data. Take a look at the code below, I shall explain the details of the code subsequently:

package net.javabeat;
import java.io. *;
import java.util.zip. *;

public class Compressor {
	 // ------------------------------------------------ Constants
	   static int BUFFER_SIZE = 2048; // 2kb

	   // ------------------------------------------------ Public Methods
	   public void compress (String OUTFILE) {
	      int i, count;
	      byte[] data = new byte[BUFFER_SIZE];
	      String files [];
	      File f = null;
	      BufferedInputStream origin = null;
	      FileInputStream inStream = null;
	      FileOutputStream destination = null;
	      ZipOutputStream output = null;
	      ZipEntry entry = null;

	      try {
	     destination = new FileOutputStream (OUTFILE);
		 output = new ZipOutputStream (new BufferedOutputStream (destination));
		 f = new File ("."); // All files in the directory where the Compressor class is placed
		 files = f.list();

		 for (i = 0; i<files.length; i++) {
		    File file = new File (files [i]);

		    if (file.isFile () &&! (file.getName ()). equals (OUTFILE)) {
		       System.out.println ("Compressing:" + files [i]);

		       inStream = new FileInputStream (file);
		       origin = new BufferedInputStream (inStream, BUFFER_SIZE);
		       entry = new ZipEntry (files [i]);
		       output.putNextEntry (entry);

		       while((count = origin.read (data, 0, BUFFER_SIZE))!= -1) {
			  output.write (data, 0, count);
		       }

		       origin.close ();
		    }
		 }

		 output.close ();

	      } catch(Exception e) {
		 e.printStackTrace ();
	      }
	   }// end compress ()

	   public static void main(String[] args){

		   Compressor compressor = new Compressor();
		   compressor.compress("zippedfile.zip");
	   }
}

This code basically compresses all the files placed under the directory where this class (Compressor.java) is placed. This class has a method called compress(). To use this method we need to instantiate an object of the class, as shown below:

public static void main(String[] args){
	 Compressor compressor = new Compressor();
	 compressor.compress("zippedfile.zip");
  }

This method takes String as an argument with the name of the file to be created “zippedfile.zip”.

Note: .zip extension needs to be given alongwith the name of the file.

The comments at each of the line the code below is self explanatory about the variables defined in the class.

int i, count;   2;
// Counters.
byte[] data = new byte[BUFFER_SIZE];
// This array will receive the bytes read from the file to be compressed
//See that BUFFER_SIZE is declared as an integer constant value 2048
//You can choose to read larger or smaller blocks .
String files [];
//Receive a list of files to be compressed
File f = null;
// f gives us information about the folder (input) that class is in

BufferedInputStream origin = null;
FileInputStream inStream = null;
FileOutputStream destination = null;
//Input and output streams.(See documentation package java.io for more information on these classes)
ZipOutputStream output = null;
//Output will be used to record our data in compressed form.
ZipEntry entry = null;
//Each entry from our archive ZIP

First Important Part of code:

destination = new FileOutputStream (OUTFILE);
output = new ZipOutputStream (new BufferedOutputStream (destination));
f = new File ("."); // All files in the directory where the Compressor class is placed
files = f.list();

Here the object (output) is created that will be used to record our ZIP file. In this part we also create the array files, that receives the list of files and sub-directories under the directory where the class is.

File Compression

To be compressed, the files have to be opened, read and written from input (entry) into the ZIP file. This is done, file by file, covering the elements of the array files.We can see this in the code below:

for (i = 0; i<files.length; i++) {
	File file = new File (files [i]);

	if (file.isFile () &&! (file.getName ()). equals (OUTFILE)) {
	System.out.println ("Compressing:" + files [i]);

	inStream = new FileInputStream (file);
	origin = new BufferedInputStream (inStream, BUFFER_SIZE);
	entry = new ZipEntry (files [i]);
	output.putNextEntry (entry);

	while((count = origin.read (data, 0, BUFFER_SIZE))!= -1) {
	  output.write (data, 0, count);
	}

	origin.close ();
	}
}

See we’re only compressing files in the folder, ignoring its subfolders.You could work out changing it :).Fragment below deserves special attention.


entry = new ZipEntry (files [i]);
<pre>output.putNextEntry (entry);

Here’s what we say to output: “we are sending a new file (input)”.

Next, we need to write (2 KB, remember?) data in the ZIP file.

while((count = origin.read (data, 0, BUFFER_SIZE))!= -1) {
  output.write (data, 0, count);
}

That’s all now execute the code either your eclipse IDE or from command prompt and you would see that a .zip file by name zippedfile.zip would be created in the same directory where your Compressor.java file is placed (.zip will contain all the files, folders and subfolders).

Summary

The rest of the code is very simple, always remember that after reading or writing a file, your stream must be closed (origin.close (), output.close ()). Finally, a very simple code that can be thoroughly explored in different applications. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook

Comments

comments

About Manisha Patil

Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better