将压缩字节 [] 写入文件

Writing zipped byte[] into file

我正在尝试将压缩文件写入内存中的 byte[],然后将其写入磁盘。生成的 zip 文件已损坏。

这个有效:

try (FileOutputStream fos = new FileOutputStream(Files.createTempFile("works", ".zip").toFile());
     ZipOutputStream zos = new ZipOutputStream(fos)) {
    zos.putNextEntry(new ZipEntry("test.txt"));
    zos.write("hello world".getBytes());
    zos.closeEntry();
}

这已损坏并创建了损坏的 zip 文件:

try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
     ZipOutputStream zos = new ZipOutputStream(bos)) {
    zos.putNextEntry(new ZipEntry("test.txt"));
    zos.write("hello world".getBytes());
    zos.closeEntry();

    Files.write(Files.createTempFile("broken", ".zip"), bos.toByteArray());
}

为什么第二个不行?以及如何修复它,假设我需要对原始 byte[] 进行操作(我无法将 zip 文件直接创建到文件中,因为我需要 byte[] 用于其他目的)。

您可能希望在写入 bos 之前刷新 zos,因为它只有在 try-with-resources 之后才会关闭(因此 zos 不一定会被刷新一直到 bos 但当您将字节写入文件时)。

编辑:您需要调用 zos.finish(); 来...完成压缩。 close()方法会正常调用。