Tuesday, February 23, 2010

How to check a Zip file is corrupted or not using java.util.zip

The method below will take the zip file name as argument.
if the zip file is corrupted then it will throw exception as below.
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.(Unknown Source)
at java.util.zip.ZipFile.(Unknown Source)

in the catch block of ZipException we are catching the exception and returning the -1 as return.

if the method return type is 0 or -1 then we can say the zip file is corrupted or it is having zero length.


public int getZipFileEntries(java.io.File fileName) throws java.io.FileNotFoundException
{
ZipFile zipFile=null;
int zipEntries = 0;
try {
zipFile = new ZipFile(fileName);
zipEntries = zipFile.size();
} catch (ZipException e) {
zipEntries=-1;
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return zipEntries;
}

No comments:

Post a Comment