Thursday, September 10, 2009

Create ZIP archieve from multiple files

Following code snippet shows how to create a zip archieve from multiple files.

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ZipDemo {
static int BUFFER_SIZE = 1024;
static String zipArchieveName = "";

public static void main(String args[]) {
try {
// Reference to the file we will be adding to the zipfile
BufferedInputStream origin = null;

// Reference to zip file
FileOutputStream dest = new FileOutputStream(zipArchieveName);

// Wrap our destination zipfile with a ZipOutputStream
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

// Create a byte[] buffer that we will read data from the source
// files into and then transfer it to the zip file
byte[] data = new byte[BUFFER_SIZE];

List files = new ArrayList();

// Iterate over all of the files in list
for (Iterator i = files.iterator(); i.hasNext();) {
// Get a BufferedInputStream that we can use to read the source file
String filename = (String);
System.out.println("Adding: " + filename);
FileInputStream fi = new FileInputStream(filename);
origin = new BufferedInputStream(fi, BUFFER_SIZE);

// Setup the entry in the zip file
ZipEntry entry = new ZipEntry(filename);

// Read data from the source file and write it out to the zip file
int count;
while ((count =, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);

// Close the source file

// Close the zip file
catch (Exception e) {

No comments: