2

我们如何在解压之前检查 zip 文件是否损坏或有效的 Zip 文件

我的代码`

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) {;} }
    }
}

`

这适用于有效的 zipfile,但无效的 zipfile 它不会抛出任何异常,不会产生任何东西,但我需要在解压缩之前确认 zip 文件的有效性

4

2 回答 2

1

只要 Zip 文件存在其 zip 条目目录,它就有效。如果您使用 zip 命令,只要目录存在,它将允许您浏览。用于测试的参数实际上执行提取和 CRC 校验。

您可以做的是使用 Java 的 temp dir 创建工具提取临时文件夹并进行 CRC 检查。然后,如果一切都成功,则通过将文件从临时目录复制到最终目标来提交提取。

于 2012-05-11T11:02:34.420 回答
1

我认为检查 zip 文件是否已损坏几乎没有用,原因有两个:

  1. 一些 zip 文件包含的字节数不仅仅是 zip 部分。例如,自解压档案有一个可执行部分,但它们仍然是有效的 zip。
  2. 该文件可能被损坏而不改变其大小。

因此,我建议计算 CRC 以获得有保证的检查损坏的方法。

于 2012-05-11T10:51:59.403 回答