写入文件以下代码时,我得到无效的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();
    }

我究竟做错了什么?

最佳答案

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

由于不需要关闭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();
}

10-04 17:03