---
title: "Java调用Ant API用法"
author: "huwanshan"
date: "2008-12-20T20:31:57Z"
tags: ["Ant", "CVS", "Java", "编程", "脚本"]
slug: "java-ant-api"
draft: false
lastmod: "2008-12-20T20:31:57Z"
id: 298026
url: "https://javabbs.iteye.com/blog/298026"
---

Java调用Ant API用法
 用法 API 调用 JAVA 
Ant是Java程序员的一个好的工具，主要可以帮助程序员进行java项目的的管理，包括批量编译、部署、文档生成等工作，其用途远不止如此，ant内置了大量的API进行各种文件系统操作，在各种应用服务器中都被广泛应用于程序和资源的部署。
 
Ant功能强大的地方在于，程序员不仅能通过编写Ant的脚本（build.xml）来进行各种文件部署管理操作，还可以通过调用Ant的丰富的API，甚至扩展Ant的API进行编程。
 
用于介绍Ant 脚本编写的书比较多，而介绍Java 调用 Ant API的书籍和资料比较少，初学者用户在进行Ant编程时会遇到不少麻烦，笔者也是在项目开发过程中，逐渐摸索并掌握了一些Java调用Ant API的一些方法和技巧，并将常用的案例收集起来呈现给大家（本文使用Ant 1.7.0版本），以供大家参考。当然，Ant的API非常丰富，本文仅做抛砖引玉之用，更强大的功能还需要读者自己在结合Ant的API进行摸索和领悟。
 
1．  目录操作：
1）  创建目录


Project prj=new Project(); 
Mkdir mkdir=new Mkdir(); 
mkdir.setProject(prj); 
mkdir.setDir(new File("d:tempdir1")); 
mkdir.execute(); 

2）  删除目录


Project prj=new Project(); 
Delete delete=new Delete(); 
delete.setProject(prj); 
delete.setDir(new File("d:tempdir1")); //可同时将子目录及所有文件删除 
delete.execute(); 

注：对每一个Ant Task，如Mkdir，Delete、Copy、Move、Zip等，都必须设置一个Project对象，可以几个Ant Task共用一个Project对象，但不能有Ant Task不设置Project对象。
 
2. 文件拷贝和移动、更名
1）文件copy


Project prj=new Project(); 
Copy copy=new Copy(); 
copy.setProject(prj); 
copy.setFile(new File("d:tempf1.txt"); 
copy.setTodir(new File("d:tempdir1")); 
copy.execute(); //将f1.txt文件copy到dir1中 

2）copy文件并同时替换其中的内容， 如将 xml中的 @eosapp_name@ 替换成真正的应用名称


Project prj=new Project(); 
Copy copy = new Copy(); 
copy.setEncoding("UTF-8"); 
copy.setProject(prj); 
copy.setTodir("d:temp"); 

FileSet fileSet=new FileSet(); 
fileSet.setDir(new File(eosHome+"/base/template.app")); 
fileSet.setIncludes("**/*.xml"); 
copy.addFileset(fileSet); 

FilterSet filter=copy.createFilterSet(); 
filter.addFilter("eosapp_name","app1"); 
copy.execute(); 

2）文件或目录移动
Move的用法和Copy用法基本一致，Move本身为Copy的子类。


Project prj=new Project(); 
Copy copy=new Copy(); 
copy.setProject(prj); 
copy.setFile(new File("d:tempf1.txt"); 
copy.setTodir(new File("d:tempdir1")); 
copy.execute(); //将f1.txt文件移动到dir1中 

3）文件改名：


Project prj=new Project(); 
Copy copy=new Copy(); 
copy.setProject(prj); 
copy.setFile(new File("d:tempf1.txt"); 
copy.setTodir(new File("d:tempf2.txt")); 
copy.execute(); //将f1.txt文件更名为f2.txt中 

4）目录更名：


Project prj=new Project(); 
Copy copy=new Copy(); 
copy.setProject(prj); 
copy.setFile(new File("d:tempdir1"); 
copy.setTodir(new File("d:tempdir2")); 
copy.execute(); //将dir1目录更名为dir2,相当于将dir1目录下的所有文件移到dir2目录下 

3．使用文件集 FileSet
使用文件集可以同时将多个满足匹配条件的文件集合进行copy、move和压缩等操作。


Project prj=new Project(); 
Copy copy=new Copy(); 
copy.setProject(prj); 
copy.setTodir(new File("d:temptodir")); 

FileSet fs=new FileSet(); 
fs.setProject(prj); 
fs.setDir(new File("d:javaprjsrc")); 
fs.setIncludes("**/*.*"); //包含所有文件 
fs.setExcludes("**/CVS,**/*.class"); //排除CVS相关文件，以及.class文件 
copy.addFileset(fs); 

copy.execute(); 

注： FileSet的setIncludes, 和setExcludes方法输入pattern, pattern是一个使用“，”或空格分隔的匹配字符串，其中， “**”代表所有文件或目录，“*.*”代表说有文件， “*.java”代表所有扩展名为java的文件。
 
4．目录扫描，查找文件


DirectoryScanner ds=new DirectoryScanner(); 
ds.setBasedir(new File("d:tempwar")); 
ds.setIncludes(new String[] ); 
ds.scan(); 
if(ds.getIncludedFilesCount()>0) { 
System.out.println("found jsp!"); 
String[] includeFiles=ds.getIncludedFiles(); 
for(String file:includeFiles){ 
System.out.println(file); 
} 
} 

5．文件压缩，打包
//压缩为zip文件


Project prj=new Project(); 
Zip zip=new Zip(); 
zip.setProject(prj); 
zip.setDestFile(new File("d:tempsrc.zip")); 
FileSet fileSet=new FileSet(); 
fileSet.setProject(prj); 
fileSet.setDir(new File("d:javaprjprj1src")); 
fileSet.setIncludes("**/*.java"); 
zip.addFileset(fileSet); 
zip.execute(); 

//将class文件打成jar包 
Project prj=new Project(); 
Jar jar=new Jar(); 
jar.setProject(prj); 
jar.setDestFile(new File("d:tempprj1.jar")); 
FileSet fileSet=new FileSet(); 
fileSet.setProject(prj); 
fileSet.setDir(new File("d:javaprjprj1bin")); 
fileSet.setIncludes("**/*.class,**/*.properties"); 
jar.addFileset(fileSet); 
jar.execute(); 

6．文件解压
1）将压缩文件中的所有文件解压


Project prj=new Project(); 
Expand expand=new Expand(); 
expand.setProject(prj); 
expand.setSrc(new File("d:tempsrc.zip")); 
expand.setOverwrite(overwrite); 
expand.setDest("d:tempoutsrc"); 
expand.execute(); 

2）将压缩文件中的符合匹配条件的文件解压


Project prj=new Project(); 
Expand expand=new Expand(); 
expand.setProject(prj); 
expand.setSrc(new File("d:tempsrc.zip")); 
expand.setOverwrite(overwrite); 
expand.setDest("d:tempoutsrc"); 
PatternSet patternset = new PatternSet(); 
patternset.setIncludes("**/*.java"); 
patternset.setProject(prj); 
expand.addPatternset(patternset); 
expand.execute(); 

3）利用Mapper解压文件: 如将 .../lib/*.jar 解压到 .../WEB-INF/lib目录下（去除目录结构）


Expand expand = new Expand(); 
expand.setProject(prj); 
expand.setSrc(new File(zipFilePath)); 
expand.setDest(new File(webDir+"/WEB-INF/lib")); 

PatternSet pattern = new PatternSet(); 
pattern.setIncludes("lib/*.jar"); 
expand.addPatternset(pattern); 

FileNameMapper mapper=new FlatFileNameMapper(); 
expand.add(mapper); 

/* another way using mapper 
Mapper mapper=expand.createMapper(); 
MapperType type=new MapperType(); 
type.setValue("flatten"); 
mapper.setType(type); 
*/ 
expand.execute(); 

7．读取zip文件
1） 读取zip文件中的文件和目录


ZipFile zipfile = new ZipFile(new File(filepath)); 
for (Enumeration entries = zipfile.getEntries(); entries.hasMoreElements();) { 
ZipEntry entry = (ZipEntry) entries.nextElement(); 
if(entry.isDirectory()) 
System.out.println("Directory: "+entry.getName()); 
else 
System.out.println("file: "+entry.getName()); 
} 
zipfile.close(); //ZipFile用完必须close，否则文件被锁定 

2）zip文件扫描,在Zip文件中查找目录或文件

ZipScanner scan=new ZipScanner(); 
scan.setSrc(new File("d:temptest.zip")); 
scan.setIncludes(new String[] ); //查找目录（一、二级目录）； 
scan.scan(); 
String dirs[]=scan.getIncludedDirectories(); 
scan.setIncludes(new String[]); //查找文件 
scan.scan(); 
String files[]=scan.getIncludedFiles(); 