Hello there everyone. I have a problem with trying to zip up directories with empty folders in them. They zip fine with my code, but according to winzip, the number of files in the archive is incorrect. It's supposed to have a total of 288 files in it, but when it's zipped up, it only says 284. I mention specifically the "empty directories" note because the zipping works fine without empty folders.
Below is the code for the zip method:
public static void zip(File[] list, File zipfile, File zipRoot)
throws IOException {
if (!zipfile.exists()) {
zipfile.createNewFile();
}
else if (!zipfile.isFile()) {
throw new IOException("The zip file, " + zipfile.getAbsolutePath()
+ " is not a file.");
}
if (list.length == 0) {
LOG.error("The list of files to zip up is empty.");
}
for (int i = 0; i < list.length; i++) {
if (!list.exists()) {
throw new IOException("The file or directory, " + list[i].getAbsolutePath()
+ " does not exist.");
}
}
FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i = 0; i < list.length; i++) {
if (LOG.isDebugEnabled())
LOG.debug(i + ": " + list[i].getName());
String entryName = getRelativeName(list[i], zipRoot);
if (list[i].isDirectory()){
if (list[i].listFiles().length == 0){
ZipEntry entry = new ZipEntry(entryName + "/");
zos.putNextEntry(entry);
}
}
else {
ZipEntry ze = new ZipEntry(entryName);
zos.putNextEntry(ze);
byte[] buffer = new byte[8096];
FileInputStream fis = new FileInputStream(list[i]);
int read = 0;
read = fis.read(buffer);
if (LOG.isDebugEnabled())
LOG.debug("\tFound " + read + " bytes.");
if (read == -1){
//empty file, but add it for preservation.
//zos.write(buffer,0,0);
}
while (read != -1) {
zos.write(buffer, 0, read);
read = fis.read(buffer);
}
fis.close();
zos.closeEntry();
}
}
zos.close();
}
The files look like they're there, but I need the system to be able to determine the number correctly.
Here's the interesting thing: It zips the files, and then when I use the size() method for zip files in java, it says 284 files. But when I unzip, it says 288 again. It's like there's files missing when compressed, but when decompressed, they return. Note that the files are actually there. If I open the archive in a third party app such as Winzip AND Winrar AND IZarc, they all show 288 files. Any idea what would make the number of files appear incorrectly in a zip file when zipped by java with the code above? Thanks in advance.
- Chris