1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
/* Create Zip File From Multiple Files using ZipOutputStream Example This Java example shows how create zip file containing multiple files using Java ZipOutputStream class. */ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipOutputStream; public class CreateZipMultipleFiles { public static void main(String args[]) { try { String zipFile = "C:/FileIO/zipdemo.zip"; String[] sourceFiles = {"C:/sourcefile1.doc", "C:/sourcefile2.doc"}; //create byte buffer byte[] buffer = new byte[1024]; /* * To create a zip file, use * * ZipOutputStream(OutputStream out) * constructor of ZipOutputStream class. */ //create object of FileOutputStream FileOutputStream fout = new FileOutputStream(zipFile); //create object of ZipOutputStream from FileOutputStream ZipOutputStream zout = new ZipOutputStream(fout); for(int i=0; i < sourceFiles.length; i++) { System.out.println("Adding " + sourceFiles[i]); //create object of FileInputStream for source file FileInputStream fin = new FileInputStream(sourceFiles[i]); /* * To begin writing ZipEntry in the zip file, use * * void putNextEntry(ZipEntry entry) * method of ZipOutputStream class. * * This method begins writing a new Zip entry to * the zip file and positions the stream to the start * of the entry data. */ zout.putNextEntry(new ZipEntry(sourceFiles[i])); /* * After creating entry in the zip file, actually * write the file. */ int length; while((length = fin.read(buffer)) > 0) { zout.write(buffer, 0, length); } /* * After writing the file to ZipOutputStream, use * * void closeEntry() method of ZipOutputStream class to * close the current entry and position the stream to * write the next entry. */ zout.closeEntry(); //close the InputStream fin.close(); } //close the ZipOutputStream zout.close(); System.out.println("Zip file has been created!"); } catch(IOException ioe) { System.out.println("IOException :" + ioe); } } } /* Output of this program would be Adding C:/sourcefile1.doc Adding C:/sourcefile2.doc Zip file has been created! */ |
Excellent and easy to follow code; best one I found after searching. Thanks!