Search code examples
javaandroidzipunzipzipinputstream

ZipInputStream check whether zip file valid before going to extract it


How we check whether zip file corrupted or valid Zip file before going to extract it

my code`

import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public void unzip() {
        FileInputStream fin = null;
        ZipInputStream zin = null;
        OutputStream fout = null;

    File outputDir = new File(_location);
    File tmp = null;

    try {
        fin = new FileInputStream(_zipFile);
        zin = new ZipInputStream(fin);
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
            Log.d("Decompress", "Unzipping " + ze.getName());

            if (ze.isDirectory()) {
                dirChecker(ze.getName());
            } else {
                tmp = File.createTempFile( "decomp", ".tmp", outputDir );
                fout = new BufferedOutputStream(new FileOutputStream(tmp));
                DownloadFile.copyStream( zin, fout, _buffer, BUFFER_SIZE );
                zin.closeEntry();
                fout.close();
                fout = null;
                tmp.renameTo( new File(_location + ze.getName()) );
                tmp = null; 
            }
        }
        zin.close();
        zin = null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if ( tmp != null  ) { try { tmp.delete();     } catch (Exception ignore) {;} }
        if ( fout != null ) { try { fout.close();     } catch (Exception ignore) {;} }
        if ( zin != null  ) { try { zin.closeEntry(); } catch (Exception ignore) {;} }
        if ( fin != null  ) { try { fin.close();      } catch (Exception ignore) {;} }
    }
}

`

this work fine with valid zipfile, but invalid zipfile it doesen't throw any exception not produce anything, but i need to confirm the validity of zip file before going to unzip it


Solution

  • I think it's pretty much useless for checking if the zip file is corrupted for two reasons:

    1. Some zip files contain more bytes than just the zip part. For example, self-extracting archives have an executable part yet they're still valid zip.
    2. The file can be corrupted without changing its size.

    So, I suggest calculating the CRC for a guaranteed method of checking for corruption.