利用ant中的org.apache.tools.ant.taskdefs.Zip来实现,首先下载和导入ant.jar包
1、件压缩代码如下:
import java.io.File;
import java.io.IOException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
public class testZip {
public static void main(String []args) throws IOException{
String destPathName = "D:\\test\\aaaa.zip";
String srcPathName = "D:\\test\\aaaa";//aaaa是一个目录
File zipFile = new File(pathName);
File srcdir = new File(srcPathName);
if(!srcdir.exists()){
System.out.println("No such file!");
return;
}
Project project = new Project();
Zip zip = new Zip();
zip.setProject(project);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(project);
fileSet.setDir(srcdir);
zip.addFileset(fileSet);
zip.execute();
}
}
2、文件解压代码:
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
public class unZip {
public static void main(String[]args) throws UnsupportedEncodingException{
String zipPath = "D:\\aaa.zip";
String destPath = "D:\\aaa";
File zipFile = new File(zipPath);
if(!zipFile.exists()){
System.out.println("ZipFile is not exist!");
return;
}
Project project = new Project();
Expand expand = new Expand();
expand.setProject(project);
expand.setTaskType("unzip");
expand.setTaskName("unzip");
expand.setSrc(zipFile);
expand.setDest(new File(destPath));
expand.setEncoding("UTF-8");
expand.execute();
}
}