【问题标题】:Invalid zip file getting generated from a byte array从字节数组生成的 zip 文件无效
【发布时间】:2021-09-01 11:40:29
【问题描述】:

我正在尝试压缩一组文件并将其存储到内存中。 下面是我正在使用的代码


        try (ByteArrayOutputStream zipBaos = new ByteArrayOutputStream();
                ZipOutputStream zs = new ZipOutputStream(zipBaos)) {
            Path pp = Paths.get(sourceDirPath);
            Files.walk(pp)
                    .filter(path -> !Files.isDirectory(path) && pp.relativize(path).toString().contains(instituteId)
                            && pp.relativize(path).toString().contains("dumps-" + hostCount))
                    .forEach(LambdaExceptionUtil.rethrowConsumer(path -> {

                        ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
                        try {
                            downloadedfilename.add(zipEntry.getName().substring(
                                    zipEntry.getName().lastIndexOf(File.separator) + 1, zipEntry.getName().length()));
                            zs.putNextEntry(zipEntry);
                            Files.copy(path, zs);
                            zs.closeEntry();
                        } catch (IOException e) {

                            LOGGER.error("Exception in Zipping downloaded files {}", e);
                            throw e;

                        }
                    }));
            return zipBaos.toByteArray();
        }

    }

现在稍后当我尝试将此字节数组内容以 zip 文件的形式再次存储在文件系统中时 FileUtils.writeByteArrayToFile(new File(location + File.separator + name), content); 正在创建 Zip 文件,并且它也显示了适当的大小。 但是当我试图打开文件窗口时抱怨它是无效的。

注意:我可以用 7Zip 打开它,但不能用 Windows 资源管理器打开。

谢谢。

【问题讨论】:

    标签: java io zip


    【解决方案1】:

    添加 ZipOutputStream finish() 和 flush() 解决了这个问题

    zs.finish();
    zs.flush();
    return zipBaos.toByteArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-28
      • 2020-09-08
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多