Creating ZIP file in memory

I need to create a ZIP file which consists of files that are created on-the-fly and have no persistence on the file system.

For example: I want to create an SQLite database in memory and after populating it with data I want to add it to a – not yet existing – ZIP file and than I want to actually write this ZIP file to the file system.

I found several approaches where the files, which are going to be the content of the archive, have to be read from the file system.

Is there actually a way to archive what I want to do? I hoped that compress-commons would help me but apparently they don’t.

Do I miss something?

If the in memory object you are trying to zip is serializable, then this is quite easy.

You can take any serializable instance and turn it in to a byte[]. I have a utility method to do this:

public static byte[] convertToBytes(Object object) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos)) {
        return bos.toByteArray();

Once you have a that object represented in bytes, you can use a ZipOutputStream to zip it up:

try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
         GZIPOutputStream out = new GZIPOutputStream(bos); ) {
    byte[] compressed = bos.toByteArray(); // this is my compressed data

(I use Gzip here for simplicity but you can also create a zip with multiple entries, for example).