1. 程式人生 > >java 壓縮/解壓 zip 多個檔案和資料夾

java 壓縮/解壓 zip 多個檔案和資料夾

參考了幾篇文章,基本都是壓縮單個檔案或者一個資料夾,不能混合壓縮。
找了一個不需要額外jar包的程式碼上改的。(參考文章)

不需要額外jar包。

壓縮方法:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import
java.util.zip.ZipOutputStream; public class ZipUtil { private static final int BUFFER_SIZE = 2 * 1024; /** * @param srcDir 壓縮資料夾路徑 * @param out 壓縮檔案輸出流 * @param KeepDirStructure 是否保留原來的目錄結構, * true:保留目錄結構; * false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗) * @throws
RuntimeException 壓縮失敗會丟擲執行時異常 */
public static void toZip(String[] srcDir, String outDir, boolean KeepDirStructure) throws RuntimeException, Exception { OutputStream out = new FileOutputStream(new File(outDir)); long start = System.currentTimeMillis(); ZipOutputStream zos = null
; try { zos = new ZipOutputStream(out); List<File> sourceFileList = new ArrayList<File>(); for (String dir : srcDir) { File sourceFile = new File(dir); sourceFileList.add(sourceFile); } compress(sourceFileList, zos, KeepDirStructure); long end = System.currentTimeMillis(); System.out.println("壓縮完成,耗時:" + (end - start) + " ms"); } catch (Exception e) { throw new RuntimeException("zip error from ZipUtils", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 遞迴壓縮方法 * @param sourceFile 原始檔 * @param zos zip輸出流 * @param name 壓縮後的名稱 * @param KeepDirStructure 是否保留原來的目錄結構, * true:保留目錄結構; * false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗) * @throws Exception */ private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception { byte[] buf = new byte[BUFFER_SIZE]; if (sourceFile.isFile()) { zos.putNextEntry(new ZipEntry(name)); int len; FileInputStream in = new FileInputStream(sourceFile); while ((len = in.read(buf)) != -1) { zos.write(buf, 0, len); } // Complete the entry zos.closeEntry(); in.close(); } else { File[] listFiles = sourceFile.listFiles(); if (listFiles == null || listFiles.length == 0) { if (KeepDirStructure) { zos.putNextEntry(new ZipEntry(name + "/")); zos.closeEntry(); } } else { for (File file : listFiles) { if (KeepDirStructure) { compress(file, zos, name + "/" + file.getName(), KeepDirStructure); } else { compress(file, zos, file.getName(), KeepDirStructure); } } } } } private static void compress(List<File> sourceFileList, ZipOutputStream zos, boolean KeepDirStructure) throws Exception { byte[] buf = new byte[BUFFER_SIZE]; for (File sourceFile : sourceFileList) { String name = sourceFile.getName(); if (sourceFile.isFile()) { zos.putNextEntry(new ZipEntry(name)); int len; FileInputStream in = new FileInputStream(sourceFile); while ((len = in.read(buf)) != -1) { zos.write(buf, 0, len); } zos.closeEntry(); in.close(); } else { File[] listFiles = sourceFile.listFiles(); if (listFiles == null || listFiles.length == 0) { if (KeepDirStructure) { zos.putNextEntry(new ZipEntry(name + "/")); zos.closeEntry(); } } else { for (File file : listFiles) { if (KeepDirStructure) { compress(file, zos, name + "/" + file.getName(), KeepDirStructure); } else { compress(file, zos, file.getName(), KeepDirStructure); } } } } } } public static void main(String[] args) throws Exception { String[] srcDir = { "C:\\Users\\LiuHY\\Desktop\\java", "C:\\Users\\LiuHY\\Desktop\\java2", "C:\\Users\\LiuHY\\Desktop\\fortest.txt" }; String outDir = "C:\\Users\\LiuHY\\Desktop\\aaa.zip"; ZipUtil.toZip(srcDir, outDir, true); } }

解壓

/**
   *
   * @Description (解壓)
   * @param zipPath zip路徑
   * @param charset 編碼
   * @param outPutPath 輸出路徑
   */
public static void decompression(String zipPath, String charset, String outPutPath) {
       long startTime=System.currentTimeMillis();  
       try {  
           ZipInputStream Zin=new ZipInputStream(new FileInputStream(zipPath), Charset.forName(charset));//輸入源zip路徑  
           BufferedInputStream Bin=new BufferedInputStream(Zin);  
           String Parent = outPutPath; //輸出路徑(資料夾目錄)  
           File Fout=null;  
           ZipEntry entry;  
           try {  
               while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){  
                   Fout=new File(Parent,entry.getName());  
                   if(!Fout.exists()){  
                       (new File(Fout.getParent())).mkdirs();  
                   }  
                   FileOutputStream out=new FileOutputStream(Fout);  
                   BufferedOutputStream Bout=new BufferedOutputStream(out);  
                   int b;  
                   while((b=Bin.read())!=-1){  
                       Bout.write(b);  
                   }  
                   Bout.close();  
                   out.close();  
                   System.out.println(Fout+"解壓成功");      
               }  
               Bin.close();  
               Zin.close();  
           } catch (IOException e) {  
               // TODO Auto-generated catch block  
               e.printStackTrace();  
           }  
       } catch (FileNotFoundException e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
       }  
       long endTime=System.currentTimeMillis();  
       System.out.println("耗費時間: "+(endTime-startTime)+" ms");
   }