I’ve looked through the recent questions on this, but I cannot find a solution to my problem. I need to zip a directory containing a bunch of directories that all containing content (basically text files). When I open the zip, I want to get the same list of directories back.
My problem is that I can zip the content, but my zip file either comes out with just the plain files (no directories) or it comes out corrupted. Has anyone done this?
The code I am posting has been producing corrupt or seemingly empty zips. Here are my methods (summarized)
public zipDir
File dirObj = new File(fileDirectory);
String outFilename = zipDirectory+File.separatorChar+filename+".zip";
log.info("Zip Directory: " + outFilename);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
System.out.println("Creating : " + outFilename);
addDir(dirObj, out);
out.close();
addDir
File[] files = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDir(files[i], out);
continue;
}
FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
System.out.println(" Adding: " + files[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}
Main
zipDir(filename, properties);
I found a solution. This code does exactly what I need. It zips a directory and maintains the directory structure.