1 2 3 // This code shows how to zip multiple files 4 5 import java.awt.*; 6 import java.awt.event.*; 7 import javax.swing.*; 8 import java.util.zip.* ; 9 import java.io.*; 10 11 12 void jButton1_actionPerformed(ActionEvent e) { 13 JFileChooser jFileChooser1 = new JFileChooser(); 14 jFileChooser1.setMultiSelectionEnabled(true); 15 jFileChooser1.setDialogTitle("Select files to Zip"); 16 jFileChooser1.setApproveButtonText("Zip It!"); 17 File[] slFiles={}; //creates an empty array of files 18 if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) { 19 slFiles = jFileChooser1.getSelectedFiles(); 20 21 } 22 this.repaint(); 23 24 if (slFiles.length>0 ){ 25 // Create a buffer for reading the files 26 byte[] buf = new byte[8192]; 27 28 try { 29 // Create the ZIP file 30 String outFilename = "c:\\files.zip";//set output file 31 ZipOutputStream out = new ZipOutputStream(new FileOutputStream( 32 outFilename)); 33 34 // Compress the files 35 for (int i = 0; i < slFiles.length; i++) { 36 FileInputStream in = new FileInputStream(slFiles[i].getName()); 37 38 // Add ZIP entry to output stream. 39 out.putNextEntry(new ZipEntry(slFiles[i].getName())); 40 41 // Transfer bytes from the file to the ZIP file 42 int len; 43 while ( (len = in.read(buf)) > 0) { 44 out.write(buf, 0, len); 45 } 46 47 // Complete the entry 48 out.closeEntry(); 49 in.close(); 50 } 51 52 // Complete the ZIP file 53 out.close(); 54 } 55 catch (IOException e1) { 56 } 57 } 58 } 59 60