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.zip.*;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.io.*;

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

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();
files.add("/tmp/systemInfo.txt");
files.add("/tmp/osgiInfo.txt");
files.add("/tmp/errorInfo.txt");

// 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) i.next();
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);
out.putNextEntry(entry);

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

// Close the source file
origin.close();
}

// Close the zip file
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

No comments: