Creating a Zip Archive


// writing a zip file ZipOutputStream out =    new ZipOutputStream(           new FileoutputStream(zipFileName)); FileInputStream in = new FileInputStream(fileToZip1); out.putNextEntry(new ZipEntry(fileToZip1)); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) {     out.write(buf,0,len); } out.closeEntry(); in.close(); out.close();



In the previous phrase, we showed how you can read from a Zip file. In this phrase, we create a Zip file. To do this, we first construct a ZipOutputStream by passing to its constructor a FileOutputStream object pointing to the file we want to create as our Zip file. We then create a FileInputStream for a file that we want to add to our Zip file. We use the putNextEntry() method of the ZipOutputStream to add the file to our Zip archive. The putNextEntry() method takes a ZipEntry object as input, so we must construct the ZipEntry from the name of the file we are adding to our archive. In a while loop, we then read in our file using the FileInputStream and write it out to the ZipOutputStream. After that is complete, we close the entry using the closeEntry() method of the ZipOutputStream, and then we close each of our open streams.

In this phrase, we have added just one file to our Zip archive, but the code would be easy to extend to add an arbitrary number of files to our Zip archive. The ZipOutputStream class supports both compressed and uncompressed entries.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net