bz3x
bz3x

Reputation: 181

Write byte array to ZipArchiveOutputStream

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

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!

Upvotes: 2

Views: 6288

Answers (1)

roehrijn
roehrijn

Reputation: 1427

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?

Upvotes: 9

Related Questions