【问题标题】:Invalid zip while compressing with ZipOutputStream使用 ZipOutputStream 压缩时 zip 无效
【发布时间】:2020-07-04 04:43:34
【问题描述】:

在写入以下代码时,我得到了无效的 zip:

public static byte[] zip(final Map<String, byte[]> mapReports) {

  try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ZipOutputStream zos = new ZipOutputStream(baos)) {
    for (Map.Entry<String, byte[]> report : mapReports.entrySet()) {
      ZipEntry entry = new ZipEntry(report.getKey());
      zos.putNextEntry(entry);
      zos.write(report.getValue());
      zos.closeEntry();
    }
    return baos.toByteArray();
  } catch (Exception e) {
    throw new RuntimeException("Exception zipping files", e);
  }
}

我将它写入文件的方式是:

    byte[] zip = zip(mapReports);
    File file = new File("demo.zip");

    try {
        OutputStream os = new FileOutputStream(file);
        os.write(zip);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

我做错了什么?

【问题讨论】:

  • 使用 FileOutputStream 代替 ByteArrayOutputStream,基于 File 类型的第二个方法参数。如果您尝试将整个内容保存在内存中,那么当您拥有大量数据时,您的程序的性能将会下降。对于非常大量的数据,性能损失将是残酷的。

标签: java zipoutputstream


【解决方案1】:

在调用baos.toByteArray() 之前,您需要close()finish() ZipOutputStream

由于ByteArrayOutputStream 不需要关闭,并且/或者即使在它关闭后您也可以调用toByteArray(),我建议您将其移到try 块之外:

public static byte[] zip(final Map<String, byte[]> mapReports) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try (ZipOutputStream zos = new ZipOutputStream(baos)) {
    for (Map.Entry<String, byte[]> report : mapReports.entrySet()) {
      zos.putNextEntry(new ZipEntry(report.getKey()));
      zos.write(report.getValue());
    }
  } catch (Exception e) {
    throw new RuntimeException("Exception zipping files", e);
  }
  return baos.toByteArray();
}

【讨论】:

    【解决方案2】:

    问题是我在关闭 ZipOutputStream 之前返回了一个值。 应该是:

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try (ZipOutputStream zos = new ZipOutputStream(baos)) {
        ....
      } catch (Exception e) {
        throw new RuntimeException("Exception zipping files", e);
      }
     return baos.toByteArray();
    

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      相关资源
      最近更新 更多