URGENT Zip file Creation problem
Hi,
I am in desperate need of some help creating a zip file using Java. I have looked at lots of sample code on the net for this but none seems to work. This code I am developing will not simply be zipping a handful of files but will be zipping a folder which contains folders, which may in turn contain files or folders, and so on and so forth.
Does anyone know any really good sites, or examples which will work for this as it is now getting really frustrating. spent an entire 8 hours on this yesterday and got nowhere.
much appreciated
[564 byte] By [
jonesy21a] at [2007-10-2 23:53:18]

> I apologise. I was not aware of this
Ok, now you know.
As for your problem; I whipped up some code that'll do what you want, I think. I did comment it, neither tested it, but it'll give you an impression how to solve it. Adjust it to your needs.
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.zip.*;
public class ZipFolderDemo {
public ZipFolderDemo(String folder, String zipname) {
List<String> filenames = scanFolder(folder, new ArrayList<String>());
zipFiles(filenames, zipname);
System.out.println("Zipped "+filenames.size()+" file(s) to: \""+zipname+"\".");
}
private List<String> scanFolder(String folder, List<String> fileNames) {
String[] files = (new File(folder)).list();
for(int i = 0; i < files.length; i++) {
String f = folder+"/"+files[i];
if((new File(f)).isFile()) {
fileNames.add(f);
} else {
scanFolder(f, fileNames);
}
}
return fileNames;
}
private void zipFiles(List<String> filenames, String outFilename) {
byte[] buf = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
for (int i = 0; i < filenames.size(); i++) {
String f = filenames.get(i);
FileInputStream in = new FileInputStream(f);
out.putNextEntry(new ZipEntry(f));
System.out.println("...zipping: "+f);
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
System.out.println("...done.\n");
} catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if(args.length != 2)
throw new IllegalArgumentException("\nUsage: java "+
"ZipFolderDemo [FOLDER_NAME] [ZIP_NAME]\n");
String folder = args[0];
if(!(new File(folder)).isDirectory())
throw new IllegalArgumentException(folder+" is not a folder.");
new ZipFolderDemo(folder, args[1]);
}
}
I copied the zip-part from http://javaalmanac.com/egs/java.util.zip/CreateZip.html
Btw: I'd put http://javaalmanac.com in your bookmarks; it's a great place to find some decent example code!
Good luck.