Monday, December 28, 2009

Creating a Zip file from a Stream

Given an InputStream generated for me, i wanted to zip it up and email it. From the java almanac i saw that i could easily do this if i write the stream to disk first. But this seemed like an unnecesary step for me. All i needed to do was to attach this outputstream to my email code and get it done. So, after a bit of playing, I got it working. Here is the code:




   1: private byte[] createZipFile(InputStream in, String fileName) throws IOException {



   2:         ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();



   3:         ZipOutputStream zippedFile = new ZipOutputStream(zipOutputStream);



   4:         byte[] buf = new byte[1024];



   5:         zippedFile.putNextEntry(new ZipEntry(myFileName));



   6:         // Transfer bytes from the file to the ZIP file



   7:         int len;



   8:         BufferedInputStream bs = new BufferedInputStream(bds[0].getInputStream());



   9:         while ((len = bs.read(buf)) > 0) {



  10:             zippedFile.write(buf, 0, len);



  11:         }



  12:         zippedFile.closeEntry();



  13:         bs.close();        



  14:         zippedFile.close();



  15:         return zipOutputStream.toByteArray();



  16: } 



By wrapping the ZipOutputStream around a ByteArrayOutputStream, i am able to access the byte array and use that to attach to my email and send out.