1. 程式人生 > >ZipUtil壓縮包工具類

ZipUtil壓縮包工具類

package com.telecom.util;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.log4j.Logger;
  
/** 
 * 壓縮演算法類 
 * 實現檔案壓縮與解壓
 * 
 */  
public class ZipUtil {
	
	/** 
     * 完成的結果檔案--輸出的壓縮檔案 
     */  
    File targetFile;  
      
    public ZipUtil() {}  
      
    public ZipUtil(File target) {  
        targetFile = target;  
        if (targetFile.exists())  
            targetFile.delete();  
    }  
  
    /** 
     * 壓縮檔案 
     *  
     * @param srcfile 
     */  
    public void zipFiles(File srcfile) {  
  
        ZipOutputStream out = null;  
        try {  
            out = new ZipOutputStream(new FileOutputStream(targetFile));  
              
            if(srcfile.isFile()){  
                zipFile(srcfile, out, "");  
            } else{  
                File[] list = srcfile.listFiles();  
                for (int i = 0; i < list.length; i++) {  
                    compress(list[i], out, "");  
                }  
            }  
              
            System.out.println("壓縮完畢");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (out != null)  
                    out.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
  
    /** 
     * 壓縮單個檔案 
     *  
     * @param srcfile 
     */  
    public void zipFile(File srcfile, ZipOutputStream out, String basedir) {  
        if (!srcfile.exists())  
            return;  
  
        byte[] buf = new byte[1024];  
        FileInputStream in = null;  
  
        try {  
            int len;  
            in = new FileInputStream(srcfile);  
            out.putNextEntry(new ZipEntry(basedir + srcfile.getName()));  
  
            while ((len = in.read(buf)) > 0) {  
                out.write(buf, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (out != null)  
                    out.closeEntry();  
                if (in != null)  
                    in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * 壓縮資料夾 
     * @param dir 
     * @param out 
     * @param basedir 
     */  
    public void zipDirectory(File dir, ZipOutputStream out, String basedir) {  
        if (!dir.exists())  
            return;  
  
        File[] files = dir.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            /* 遞迴 */  
            compress(files[i], out, basedir + dir.getName() + "/");  
        }  
    }  
    
    /** 
     * 壓縮資料夾裡的檔案 
     * 起初不知道是檔案還是資料夾--- 統一呼叫該方法 
     * @param file 
     * @param out 
     * @param basedir 
     */  
    public void compress(File file, ZipOutputStream out, String basedir) {
        /* 判斷是目錄還是檔案 */  
        if (file.isDirectory()) {  
            this.zipDirectory(file, out, basedir);  
        } else {  
            this.zipFile(file, out, basedir);  
        }  
    }
    
    /**
     * 壓縮源目錄下的檔案到指定目錄
     * @param sourcePath
     * @param descDir
     */
    public static void createZipFiles(String sourcePath, String descDir)throws IOException{
    	System.out.println("******************開始壓縮********************");
    	File source = new File(sourcePath);  
        File target = new File(descDir);
        ZipOutputStream out = null;  
        try {  
            out = new ZipOutputStream(new FileOutputStream(target));  
            new ZipUtil().compress(source, out, "");  
            System.out.println("******************壓縮完畢:"+descDir+"********************");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (out != null)  
                    out.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
    }

    /**
     * 解壓到指定目錄
     * @param zipPath
     * @param descDir
     */
    public static void unZipFiles(String zipPath, String descDir)throws IOException{
        unZipFiles(new File(zipPath), descDir);
    }
    /**
     * 解壓檔案到指定目錄
     * @param zipFile
     * @param descDir
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFiles(File zipFile, String descDir)throws IOException {
    	System.out.println("******************開始解壓********************");
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
        for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
            ;
            //判斷路徑是否存在,不存在則建立檔案路徑
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            //判斷檔案全路徑是否為資料夾,如果是上面已經上傳,不需要解壓
            if (new File(outPath).isDirectory()) {
                continue;
            }
            //輸出檔案路徑資訊
            System.out.println(outPath);

            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        zip.close();
        System.out.println("******************解壓完畢********************");
    }
    
    
	public static void main(String[] args) throws IOException {
    	//壓縮
		createZipFiles("F://456", "F://test111.zip");
    	//解壓
        unZipFiles("F://test111.zip", "F://123//");
    }
}

createZipFiles() 和 unZipFiles() 的入參都是絕對路徑。 壓縮時是將最後一級資料夾全部打包壓縮: 在這裡插入圖片描述 注意:unZipFiles(File zipFile, String descDir)方法中對於新建的ZipFile程式處理結束後要close: 在這裡插入圖片描述