将压缩的字节 [] 写入文件



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

这有效:

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,因为它在尝试使用资源之前不会关闭(因此当您将字节写入文件时,zos不一定刷新到bos)。

编辑:您需要致电zos.finish();...好吧,完成压缩。close()方法将正常调用它。

最新更新