ZipUtil.java
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 6 import org.apache.tools.zip.ZipEntry; 7 import org.apache.tools.zip.ZipOutputStream; 8 9 10 /** 11 * @author Heloise.Tian 12 * 13 */ 14 public class ZipUtil { 15 16 public static String zipExportFiles(String outputFile, String files[]) throws IOException { 17 18 File f = new File(outputFile); 19 File parent = f.getParentFile(); 20 if (!parent.exists()) { 21 parent.mkdirs(); 22 } 23 24 // Create a buffer for reading the files 25 byte[] buf = new byte[1024]; 26 27 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f)); 28 // Compress the files 29 for (int i = 0, j = files.length; i < j; i++) { 30 File entryfile = new File(files[i]); 31 FileInputStream in = new FileInputStream(entryfile); 32 // Add ZIP entry to output stream. 33 34 out.putNextEntry(new ZipEntry(entryfile.getName())); 35 // Transfer bytes from the file to the ZIP file 36 int len = 0; 37 while ((len = in.read(buf)) > 0) { 38 out.write(buf, 0, len); 39 } 40 // Complete the entry 41 out.closeEntry(); 42 in.close(); 43 } 44 45 out.close(); 46 return f.getAbsolutePath(); 47 } 48 }
调用方式:
1 String[] files = {tempExcel1Path, tempExcel2Path }; 2 //Zip files. 3 ZipUtil.zipExportFiles(outZipFilePath, files);