java實現zip壓縮檔案/資料夾

螞蟻路過發表於2013-05-02
由於java.util.zip.ZipOutputStream有中文亂碼問題,所以採用org.apache.tools.zip.ZipOutputStream。 
以下是程式碼: 

import java.io.BufferedInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.zip.CRC32;  
import java.util.zip.CheckedOutputStream;  

import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;  
import org.apache.tools.zip.ZipOutputStream;  

/**
 * @ClassName: ZipCompressor
 * @CreateTime Apr 28, 2013 1:12:16 PM
 * @author : Mayi
 * @Description: 壓縮檔案的通用工具類-採用org.apache.tools.zip.ZipOutputStream實現,較複雜。
 *
 */
public class ZipCompressor {
	private Logger logger = Logger.getLogger(ZipCompressor.class);
    static final int BUFFER = 8192;  
    private File zipFile;  
    
    /**
     * 壓縮檔案建構函式
     * @param pathName 壓縮的檔案存放目錄
     */
    public ZipCompressor(String pathName) {  
        zipFile = new File(pathName);  
    }  
  
    /**
     * 執行壓縮操作
     * @param srcPathName 被壓縮的檔案/資料夾
     */
    public void compressExe(String srcPathName) {  
        File file = new File(srcPathName);  
        if (!file.exists()){
        	throw new RuntimeException(srcPathName + "不存在!");  
        }
        try {  
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);  
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,new CRC32());  
            ZipOutputStream out = new ZipOutputStream(cos);  
            String basedir = "";  
            compressByType(file, out, basedir);  
            out.close();  
        } catch (Exception e) { 
        	e.printStackTrace();
        	logger.error("執行壓縮操作時發生異常:"+e);
            throw new RuntimeException(e);  
        }  
    }  
  
    /**
     * 判斷是目錄還是檔案,根據型別(檔案/資料夾)執行不同的壓縮方法
     * @param file 
     * @param out
     * @param basedir
     */
    private void compressByType(File file, ZipOutputStream out, String basedir) {  
        /* 判斷是目錄還是檔案 */  
        if (file.isDirectory()) {  
        	logger.info("壓縮:" + basedir + file.getName());  
            this.compressDirectory(file, out, basedir);  
        } else {  
        	logger.info("壓縮:" + basedir + file.getName());  
            this.compressFile(file, out, basedir);  
        }  
    }  
  
    /**
     * 壓縮一個目錄
     * @param dir
     * @param out
     * @param basedir
     */
    private void compressDirectory(File dir, ZipOutputStream out, String basedir) {  
        if (!dir.exists()){
        	 return;  
        }
           
        File[] files = dir.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            /* 遞迴 */  
        	compressByType(files[i], out, basedir + dir.getName() + "/");  
        }  
    }  
  
    /**
     * 壓縮一個檔案
     * @param file
     * @param out
     * @param basedir
     */
    private void compressFile(File file, ZipOutputStream out, String basedir) {  
        if (!file.exists()) {  
            return;  
        }  
        try {  
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
            ZipEntry entry = new ZipEntry(basedir + file.getName());  
            out.putNextEntry(entry);  
            int count;  
            byte data[] = new byte[BUFFER];  
            while ((count = bis.read(data, 0, BUFFER)) != -1) {  
                out.write(data, 0, count);  
            }  
            bis.close();  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
}

後來發現原來可以用ant中的org.apache.tools.ant.taskdefs.Zip來實現,更加簡單。
import java.io.File;  

import org.apache.tools.ant.Project;  
import org.apache.tools.ant.taskdefs.Zip;  
import org.apache.tools.ant.types.FileSet;  
  
/**
 * @ClassName: ZipCompressorByAnt
 * @CreateTime Apr 28, 2013 1:23:45 PM
 * @author : Mayi
 * @Description: 壓縮檔案的通用工具類-採用ant中的org.apache.tools.ant.taskdefs.Zip來實現,更加簡單。
 *
 */
public class ZipCompressorByAnt {  
  
    private File zipFile;  
  
    /**
     * 壓縮檔案建構函式
     * @param pathName 最終壓縮生成的壓縮檔案:目錄+壓縮檔名.zip
     */
    public ZipCompressorByAnt(String finalFile) {  
        zipFile = new File(finalFile);  
    }  
      
    /**
     * 執行壓縮操作
     * @param srcPathName 需要被壓縮的檔案/資料夾
     */
    public void compressExe(String srcPathName) {  
        File srcdir = new File(srcPathName);  
        if (!srcdir.exists()){
            throw new RuntimeException(srcPathName + "不存在!");  
        } 
          
        Project prj = new Project();  
        Zip zip = new Zip();  
        zip.setProject(prj);  
        zip.setDestFile(zipFile);  
        FileSet fileSet = new FileSet();  
        fileSet.setProject(prj);  
        fileSet.setDir(srcdir);  
        //fileSet.setIncludes("**/*.java"); //包括哪些檔案或資料夾 eg:zip.setIncludes("*.java");  
        //fileSet.setExcludes(...); //排除哪些檔案或資料夾  
        zip.addFileset(fileSet);  
        zip.execute();  
    }  
} 


測試一下 
Java程式碼  收藏程式碼
  1. package net.szh.zip;  
  2.   
  3. public class TestZip {  
  4.     public static void main(String[] args) {  
  5.         ZipCompressor zc = new  ZipCompressor("E:\\szhzip.zip");  
  6.         zc.compress("E:\\test");  
  7.           
  8.         ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");  
  9.         zca.compress("E:\\test");  
  10.     }  
  11. }  

參考自:ITeye

相關文章