Tags

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFile {

	static final int BUFFER = 2048;	

	public ZipFile(String input, String output)	{
		try	{
	         BufferedInputStream origin = null;
	         FileOutputStream dest 	= new FileOutputStream(output);
	         ZipOutputStream out 	= new ZipOutputStream(new BufferedOutputStream(dest));
	         //out.setMethod(ZipOutputStream.DEFLATED);

	         byte data[] = new byte[BUFFER];

	         // get a list of files from current directory
	         File f = new File(input);
	         String files[] = f.list();

	         for (int i=0; i<files.length; i++) {
	            System.out.println("Adding: "+files[i]);
	            FileInputStream fi = new FileInputStream(input+files[i]);
	            origin = new BufferedInputStream(fi, BUFFER);
	            ZipEntry entry = new ZipEntry(input+files[i]);
	            out.putNextEntry(entry);
	            int count;
	            while((count = origin.read(data, 0,BUFFER)) != -1) {
	               out.write(data, 0, count);
	            }
	            origin.close();
	         }
	         out.close();
	     }
		catch(Exception e) {
	         e.printStackTrace();
	     }
	}

	public static void main(String[] args) {
		String input 	= "C:\\Program Files\\Mozilla Firefox\\";
		String output 	= ".\\output\\compress.zip";
		ZipFile app 	= new ZipFile(input,output);
	}
}

Reference: http://java.sun.com/developer/technicalArticles/Programming/compression/
Advertisements