import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
// Note: 1st arg is the zipfile to produce
public String zipMyFiles
(String zipFilePath, String
filesToZipFolder) {
String result = "";
try {
ZipOutputStream zos =
new ZipOutputStream(new
FileOutputStream(zipFilePath));
zos.setLevel
(Deflater.BEST_COMPRESSION);
// compression style
byte[] readBuffer = new byte[2156];
int bytesin = 0;
File filesFolder = new File
( filesToZipFolder );
// if filesFolder.isDirectory ???
String[] fileList = filesFolder.list();
// flat directory, no hierarchy allowed
for (int i = 0; i < fileList.length; i++) {
File f =new File(filesFolder, fileList[i]);
if (f.isDirectory()) {
// ignore it
}
else {
FileInputStream in =
new FileInputStream(f);
ZipEntry anEntry =
new ZipEntry(f.getPath());
zos.putNextEntry(anEntry);
int len;
while ((bytesin =
in.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesin);
}
zos.closeEntry();
in.close();
}
}
zos.close();
}
catch (IllegalArgumentException iae) {
iae.printStackTrace();
return "ERROR_
ILLEGALARGUMENTSEXCEPTION";
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
return "ERROR_FILENOTFOUND";
}
catch (IOException ioe) {
ioe.printStackTrace();
return "ERROR_IOEXCEPTION";
}
return "OK";
}
}
Do you have comments on this tip? Let us know.
This tip was submitted to the SearchDomino.com tip exchange by member Mark Bryson. Please let others know how useful it is via the rating scale below. Do you have a useful Notes/Domino tip or code to share? Submit it to our monthly tip contest and you could win a prize and a spot in our Hall of Fame.
This was first published in September 2004