Java进行zip包压缩/解压

package com.xiaowu.test;

import java.io.File;  
import org.apache.tools.ant.Project;  
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;  
import org.apache.tools.ant.types.FileSet; 

public class Ziper {

    private File zipFile;  
    
    public Ziper(String pathName) {  
        this.zipFile = new File(pathName);  
    }  
      
    public boolean compress(String srcPathName) {  
    	return compress(srcPathName, "", "");
    } 	
    
    public boolean compress(String srcPathName, String includes, String excludes) {  
        File srcdir = new File(srcPathName);  
        if (!srcdir.exists()){  
            System.out.println(srcPathName + "不存在!");
            return false;  
        }  
        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(includes); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");  
        fileSet.setExcludes(excludes); //排除哪些文件或文件夹  
        zip.addFileset(fileSet);            
        zip.execute(); 
        return true;
    } 	
    
    public boolean unCompress(){
		return unCompress(this.zipFile.getParent());
    }

    public boolean unCompress(String dest){
    	Expand expand = new Expand();
    	expand.setOverwrite(true);
    	expand.setSrc(this.zipFile);
    	expand.setDest(new File(dest));
    	expand.execute();
		return true; 	
    }
    
	public static void main(String[] args){
		Ziper ziper1 = new Ziper("D:/z1.zip");
		ziper1.compress("D:/com");    //把D:/com下的所有文件和子目录中的文件一起打包;不包括D:/com本身
		
		Ziper ziper2 = new Ziper("D:/z2.zip");
		ziper2.compress("D:/com",   //根目录
						"testcase/*.java",   //includes, 支持通配符匹配,多个子项时以逗号或空格分隔
						"");   //excludes, 支持通配符匹配,多个子项时以逗号或空格分隔
		
		Ziper ziper3 = new Ziper("D:/z3.zip");
		ziper3.compress("D:/com", 
						"",   //includes, 支持通配符匹配,多个子项时以逗号或空格分隔
						"testcase/testfile.xml");   //excludes, 支持通配符匹配,多个子项时以逗号或空格分隔
		
		Ziper ziper4 = new Ziper("D:/z3.zip");
		ziper4.unCompress();    //解压到当前目录
		ziper4.unCompress("E:/");     //解压到指定目录		
	}	
}

打包压缩不记得是哪找到的了,解压是自己找文档添加进去的,解压还有可以解压过滤的功能,详见JAVADoc

Zip类文档:http://www.docjar.com/docs/api/org/apache/tools/ant/taskdefs/Zip.html

Expand类文档:http://www.docjar.com/docs/api/org/apache/tools/ant/taskdefs/Expand.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值