How to check if a generated zip file is corrupted?
java, zip
Solution
You can use the `ZipFile` class to check your file :
static boolean isValid(final File file) {
ZipFile zipfile = null;
try {
zipfile = new ZipFile(file);
return true;
} catch (IOException e) {
return false;
} finally {
try {
if (zipfile != null) {
zipfile.close();
zipfile = null;
}
} catch (IOException e) {
}
}
}
Problem
we have a piece of code which generates a zip file on our system. Everything is ok, but sometimes this zip file while opened by FilZip or WinZip is considered to be corrupted. So here is my question: how can we check programatically if a generated zip file is corrupted? Here is the code we are using to generate our zip files: ``` try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tmpFile)); byte[] buffer = new byte[16384]; int contador = -1; for (DigitalFile digitalFile : document.getDigitalFiles().getContent()) { ZipEntry entry = new ZipEntry(digitalFile.getName()); FileInputStream fis = new FileInputStream(digitalFile.getFile()); try { zos.putNextEntry(entry); while ((counter = fis.read(buffer)) != -1) { zos.write(buffer, 0, counter); } fis.close(); zos.closeEntry(); } catch (IOException ex) { throw new OurException("It was not possible to read this file " + arquivo.getId()); } } try { zos.close(); } catch (IOException ex) { throw new OurException("We couldn't close this stream", ex); } ``` Is there anything we are doing wrong here? EDIT: Actually, the code above is absolutely ok. My problem was that I was redirecting the WRONG stream for my users. So, instead of opening a zip file they where opening something completely different. Mea culpa :( BUT the main question remains: how programatically I can verify if a given zip file is not corrupted?