So I was interested in appending files to a zip archive and I came across a few users who asked this question before and another user gave this code snippet as a solution to tha
Works find for me. I suspect you might want to check the operation of tmpZip.delete()
.
if (!tmpZip.exists() || tmpZip.delete()) {
// ... Continue
} else {
// ... File is locked
}
UPDATE
I've been playing around with the code and there are some additional flaws...
When adding in the old entries to the new file, you are using the existing ZipEntry
entry. This will fail if the resulting compression is different. You should create a new ZipEntry
add use that instead
ZipEntry ne = new ZipEntry(ze.getName());
out.putNextEntry(ne);
// Write bytes to file...
out.closeEntry();
You never close the ZipInputStream
which means tmpZip.delete()
at the end will fail.
You're error handling is next to non existent...
ZipInputStream zin = null;
ZipOutputStream out = null;
try {
// Append zip ...
} finally {
try {
zin.close();
} catch (Exception exp) {
}
try {
out.close();
} catch (Exception exp) {
}
}
Will prevent future file locks (I've deliberately not caught the IOException
as I personally believe it should be thrown back to the called)
You shouldn't overwrite the existing zip file UNTIL you have finished. You should create a temporary file for the new zip file, write all the files into it, append the existing files and once your done, replace the existing file with the temporary one.
This means, if something should go wrong, you've not destroyed the existing zip file.
IMHO