import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.types.FileSet; /** * @Desc:ZIP压缩 * @Date:2016-8-11 上午9:57:49 * destCompressAlfterFileName C:/tc_excel/21.zip * srcPathName C:/tc_excel/ * srcFileName EX-CHN.xls * 效果是 把EX-CHN.xls压缩成21.zip 并把EX-CHN.xls文件删除 */ public class ZipCompressorByAnt { public static int compress(String destCompressAlfterFileName,String srcPathName,String srcFileName) { try { File srcdir = new File(srcPathName); if (!srcdir.exists()) return -1; /** 文件目录不存在 */ Project prj = new Project(); Zip zip = new Zip(); zip.setProject(prj); zip.setDestFile(new File(destCompressAlfterFileName)); FileSet fileSet = new FileSet(); fileSet.setProject(prj); //fileSet.setDir(srcdir); fileSet.setFile(new File(srcPathName + srcFileName)); // fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 // eg:zip.setIncludes("*.java"); // fileSet.setExcludes(...); 排除哪些文件或文件夹 zip.addFileset(fileSet); zip.execute(); //删除源文件 File file = new File(srcPathName + srcFileName); if(file.exists()) file.delete(); return 0; /** 压缩成功 */ } catch (BuildException e) { e.printStackTrace(); return 1; /** 压缩异常 */ } } public static void main(String[] args) { ZipCompressorByAnt.compress("C:/tc_excel/21.zip", "C:/tc_excel/","EX-CHN.xls"); } }