Create a Zip File in Memory

Sleep Deprived Bulbasaur picture Sleep Deprived Bulbasaur · May 12, 2014 · Viewed 34.4k times · Source

I'm trying to zip a file (for example foo.csv) and upload it to a server. I have a working version which creates a local copy and then deletes the local copy. How would I zip a file so I could send it without writing to the hard drive and do it purely in memory?

Answer

Thirumalai Parthasarathi picture Thirumalai Parthasarathi · May 12, 2014

Use ByteArrayOutputStream with ZipOutputStream to accomplish the task.

you can use ZipEntry to specify the files to be included into the zip file.

Here is an example of using the above classes,

String s = "hello world";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {

  /* File is not on the disk, test.txt indicates
     only the file name to be put into the zip */
  ZipEntry entry = new ZipEntry("test.txt"); 

  zos.putNextEntry(entry);
  zos.write(s.getBytes());
  zos.closeEntry();

  /* use more Entries to add more files
     and use closeEntry() to close each file entry */

  } catch(IOException ioe) {
    ioe.printStackTrace();
  }

now baos contains your zip file as a stream