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