【问题标题】:Cannot unzip the zip file created using zlib in Java无法解压缩在 Java 中使用 zlib 创建的 zip 文件
【发布时间】:2019-10-22 05:13:09
【问题描述】:

我正在尝试在 Java (java.util.zip) 中使用 zlib 压缩文件,但在创建文件后无法解压缩文件。我正在使用下面的代码:

    public static ByteArrayInputStream compress(InputStream inputStream, String targetFilePath) {

        String fileName = new File(targetFilePath).getName();

        try {

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
            zipOutputStream.putNextEntry(new ZipEntry(fileName));
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

            byte[] buffer = new byte[1000];
            int len;
            while ((len = bufferedInputStream.read(buffer)) > 0) {
                zipOutputStream.write(buffer, 0, len);
            }
            bufferedInputStream.close();
            zipOutputStream.closeEntry();
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

        } catch (IOException ex) {
            log.error("The file does not exist");
        }
        return null;
    }

当我读取 sample.txt 文件并将其作为 InputStream 输入到此方法时,它会创建一个 sample.zip 文件。

但是,当我尝试使用 unzip 命令打开此 zip 文件时,它无法打开并出现以下错误:

  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of sample.zip or
        sample.zip.zip, and cannot find sample.zip.ZIP, period.

我尝试使用 jar xvf sample.zip 打开 zip,它有效并显示包含 sample.txt 文本文件。这是因为jar 命令不会在压缩文件中查找End-of-central-directory signature

有人能解释一下为什么 zip 文件中没有这个签名吗?非常感谢这方面的任何帮助。

【问题讨论】:

  • 关闭条目后调用zipOutputStream.close()能解决问题吗?
  • @dnault 解决了它! :) 非常感谢。如果您将其发布为答案,我可以将其标记为正确答案。

标签: java zip zlib unzip


【解决方案1】:

确保在写完最后一个条目后关闭ZipOutputStream。这使流有机会完成 ZIP 存档的创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多