java - ZipInputStream 在提取 zip 文件之前检查它是否有效

标签 java android zip unzip zipinputstream

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

`

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

最佳答案

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

  1. 某些 zip 文件包含的字节数多于 zip 部分。例如,自解压存档具有可执行部分,但它们仍然是有效的 zip。
  2. 文件可能会在不改变其大小的情况下被损坏。

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

关于java - ZipInputStream 在提取 zip 文件之前检查它是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10549884/

相关文章:

java - 耶拿/Fuseki : loading a custom implementation of com. hp.hpl.jena.graph.impl.GraphBase?

android - ListView 和多点触控手势

MSBuild 和创建 ZIP 文件

python - 在python中将opencv图像写入zip文件

github - 在github上上传Zip文件并在上传后解压缩

java - 如何使用 Java 泛型以便为返回类型为 List<Interface> 的方法返回 List<InterfaceImpl>

java - 在 Windows 上使用 exec-maven-plugin 执行 shell 脚本

javax.xml.ws.WebServiceException : class do not have a property of the name return when returning HashMap in web service

java - Android:构造函数内部的同步()无效?

java - 使用 Retrofit 选择某个 ID