繁体   English   中英

无法解压 Java 中使用 zlib 创建的 zip 文件

[英]Cannot unzip the zip file created using zlib in Java

I'm trying to use zlib in Java ( java.util.zip ) to zip a file, but cannot unzip the file after creating it. 我正在使用下面的代码:

    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命令不会在 zip 文件中查找End-of-central-directory signature

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM