2

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

UdayaLakmal
  • 4,035
  • 4
  • 29
  • 40

2 Answers2

1

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.

GingerHead
  • 8,130
  • 15
  • 59
  • 93
1

A Zip file will be valid as long as it has its zip entry catalog present. If you take the zip command, it will allow you to browse so long as the catalog is present. A parameter used for testing actually performs an extraction and CRC check.

What you can do is extract and do a CRC check on a temporary folder using the temp dir creation facility of Java. Then if it is all successful, commit the extract by copying the files from the temp dir to the final destination.

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265