Question

I need to create a zip file and am limited by the following conditions:

  • The entries come as byte[] (or ByteArrayOutputStream) and not as File.
  • The filenames for the entry can be non-ascii/UTF-8.
  • JDK 1.6 or earlier

Since java.util.zip only supports UTF-8 filenames from JDK 1.7 and onward, it seems better to use commons-compress ZipArchiveOutputStream. But how to create a ZipEntryArchive based on a byte array or ByteArrayOutputStream rather than a File?

Thank you!

Was it helpful?

Solution

The following method takes a byte[] as input, produces a zip and returns its content as another byte[]. All is done in memory. No IO operations on the disk. I stripped exception handling for a better overview.

    byte[] zip(byte[] data, String filename) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(bos);

        ZipArchiveEntry entry = new ZipArchiveEntry(filename);
        entry.setSize(data.length);
        zos.putArchiveEntry(entry);
        zos.write(data);
        zos.closeArchiveEntry();

        zos.close();
        bos.close();

        return bos.toByteArray();       
   }

Does this solve your problem?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top