ZipUtil工具類
阿新 • • 發佈:2017-09-18
str basepath ext dir ring [] com puts copy
說明:
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) throwsIOException { 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) throwsIOException { 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 }
ZipUtil工具類