Search code examples
javaniobytearrayoutputstreamzipoutputstream

Writing zipped byte[] into file


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).


Solution

  • You might want to flush zos before writing bos, since it won't be closed until after the try-with-resources (and therefore zos is not necessarily flushed through to bos yet when you're writing the bytes to file).

    Edit: you need to call zos.finish(); to...well finish the compression. The close() method will call it normally.