I am trying to write a zipfile to a byte[]
in memory, and then write that out to disk. The resulting zipfile is corrupt.
This works:
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();
}
This is broken and creates a corrupt zip file:
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());
}
Why would the second one not work? And how can I fix it, assuming that I need to operate on a raw byte[]
(I can't create the zip file directly into a file, since I need the byte[]
for other purposes).