ZipUtil工具类
说明:
1.平时做zip打包主要用到了java.util.zip下的ZipOutputStream、ZipEntry两个API
如需了解这两个API怎么用,请自行查阅文档。
2.以下方法已经经过测试,可直接copy使用,如有不足之处请指出。谢谢!
1 /** 2 * 压缩文件列表到某个zip包 3 * @param zipFileName zip包文件名 4 * @param paths 文件列表路径 5 * @throws IOException 6 */ 7 public static void compress(String zipFileName,String... paths) throws IOException { 8 compress(new FileOutputStream(zipFileName),paths); 9 } 10 11 12 /** 13 * 压缩文件列表到某个zip包 14 * @param stream 流 15 * @param paths 文件列表路径 16 * @throws IOException 17 */ 18 public static void compress(OutputStream stream,String... paths) throws IOException { 19 ZipOutputStream zos = new ZipOutputStream(stream); 20 for (String path : paths){ 21 if (StringUtils.equals(path,"")){ 22 continue; 23 } 24 File file = new File(path); 25 if (file.exists()){ 26 if (file.isDirectory()){ 27 zipDirectory(zos,file.getPath(),file.getName() + File.separator); 28 } else { 29 zipFile(zos,file.getPath(),""); 30 } 31 } 32 } 33 zos.close(); 34 } 35 36 37 /** 38 * 解析多文件夹 39 * @param zos zip流 40 * @param dirName 目录名称 41 * @param basePath 42 * @throws IOException 43 */ 44 private static void zipDirectory(ZipOutputStream zos,String dirName,String basePath) throws IOException { 45 File dir = new File(dirName); 46 if (dir.exists()){ 47 File files[] = dir.listFiles(); 48 if (files.length > 0){ 49 for (File file : files){ 50 if (file.isDirectory()){ 51 zipDirectory(zos,file.getPath(),file.getName() + File.separator); 52 } else { 53 zipFile(zos,file.getName(),basePath); 54 } 55 } 56 } else { 57 ZipEntry zipEntry = new ZipEntry(basePath); 58 zos.putNextEntry(zipEntry); 59 } 60 } 61 } 62 63 64 private static void zipFile(ZipOutputStream zos,String fileName,String basePath) throws IOException { 65 File file = new File(fileName); 66 if (file.exists()){ 67 FileInputStream fis = new FileInputStream(fileName); 68 ZipEntry ze = new ZipEntry(basePath + file.getName()); 69 zos.putNextEntry(ze); 70 byte[] buffer = new byte[8192]; 71 int count = 0; 72 while ((count = fis.read(buffer)) > 0){ 73 zos.write(buffer,0,count); 74 } 75 fis.close(); 76 } 77 }