23 January 2009

Create a zip archive in Java

Here's a Java class to zip up files in a directory. Thanks to the Java forum for their help in fixing some bugs.

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

public class Zipper
private String _zipFilePath = "";
private String _imageFolderPath = "";
private String _zipFileName = "";
private static final int BUFFER = 20480;
private String _error = "";

public Zipper()

public void setZipFilePath(String path)
_zipFilePath = path;

public void setImageFolderPath(String path)
_imageFolderPath = path;

public String getError()
return _error;

public void zipEm()
File directory = new File(_imageFolderPath);

File files[] = directory.listFiles();

try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFilePath);
ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(dest));

byte data[] = new byte[BUFFER];

File f = null;
ZipEntry entry = null;
FileInputStream fi = null;
int count;

// Iterate over the file list and add them to the zip file.
for (int i=0; i <files.length; i++)
fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER);
entry = new ZipEntry(files[i].getName());

while((count = origin.read(data,0,BUFFER)) != -1)
count = 0;
catch (Exception e)
// handle exception
_error = e.getMessage();


Victor Pudeyev said...

I was looking for a way to retrieve arbitrary number (100's) of blobs from a MySQL in one sitting without having the user to click 100's of times. Your script is helpful---thanks!

Alex C said...

You're welcome, Victor. Glad it helped.

Alex said...

There are a lot of files inside zip archives. But couple days some of them were crashed no one knew how. I was succeeded and accidentally detected the next tool - corrupt zip downloads repair. It determined my issue easy and free of charge as I bore in mind. Besides my sister were glad and thanked me a lot for this tool.

Alex said...

Yesterday I couldn't open my zip file with my working information. I was upset, but to my good fortune my friend suggested me - problems with winzip file. He was right it settled my problem with ease and I at sight forgot about it.