1. a.下载ant: http://ant.apache.org/bindownload.cgi
b.安装ant: 解压ant,路径越简单越好(这是好习惯),设置环境变量ANT_HOME,PATH里添加;%ANT_HOME%\bin
c.打开cmd,键入ant回车,如果出现提示信息
"Buildfile: build.xml does not exist!
Build failed"
就说明安装成功了
2. java工程目录结构:
|-src-|- //.java源文件
|-bin-|- // .class文件
|-lib-|- //第三方jar包
build.xml // ant 配置文件
3。由于ant没有提供填写jar包里Class-Path的任务,所以需要编写自定义任务,扩展Ant,Java代码如下:
- package personal.lw.util;
- import java.io.File;
- import org.apache.tools.ant.BuildException;
- import org.apache.tools.ant.Task;
- public class AntUtil extends Task {
- private String lib;
- private String classPath = "";
- private String fileType = ".jar";
- // ant task
- public void execute() throws BuildException {
- try {
- this.classPath(dir(lib));
- this.getOwningTarget().getProject().setProperty("class-path",
- classPath);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 根据路径获得目录
- private File dir(String path) throws Exception {
- return dir(path, false);
- }
- private File dir(String path, boolean bCreate) throws Exception {
- File dir = new File(path);
- if (dir.exists()) {
- if (!dir.isDirectory()) {
- throw new Exception(dir.getName() + "is not a directory !");
- }
- } else {
- if (bCreate) { // 新建
- if (!dir.mkdirs()) {
- throw new Exception("can not create the directory \""
- + dir.getName() + "\"!");
- }
- }
- }
- return dir;
- }
- // 生成classpath字符串
- private void classPath(File dir) {
- classPath(dir, lib);
- classPath = classPath.trim();
- }
- private void classPath(File dir, String parentPath) {
- // 处理目录
- if (dir.isDirectory()) {
- File[] subs = dir.listFiles();
- for (int i = 0, len = subs.length; i < len; i++) {
- if (subs[i].isFile()) { // 文件
- String name = subs[i].getName();
- // 处理.jar文件
- if (name.length() > fileType.length()
- && fileType.equals(name.substring(name.length()
- - fileType.length(), name.length()))) {
- classPath += parentPath + path(subs[i]) + " ";
- continue;
- }
- }
- if (subs[i].isDirectory()) { // 文件夹
- classPath(subs[i], parentPath + path(subs[i]));
- }
- }
- } else {
- // 不是目录
- System.out.println(dir.getPath() + dir.getName()
- + "is not a directory !");
- }
- }
- // 文件路径
- private String path(File f) {
- return "/" + f.getName();
- }
- // 字符串 -- > 路径
- @SuppressWarnings("unused")
- private String path(String path) {
- path = path.replaceAll("\\\\", "/");
- if (!"/".equals(path.substring(0, 1))) {
- path = "/" + path;
- }
- return path;
- }
- public void setLib(String lib) {
- this.lib = lib;
- }
- }
- 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liuwei_blog/archive/2008/12/20/3567292.aspx
package personal.lw.util;
import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
public class AntUtil extends Task {
private String lib;
private String classPath = "";
private String fileType = ".jar";
// ant task
public void execute() throws BuildException {
try {
this.classPath(dir(lib));
this.getOwningTarget().getProject().setProperty("class-path",
classPath);
} catch (Exception e) {
e.printStackTrace();
}
}
// 根据路径获得目录
private File dir(String path) throws Exception {
return dir(path, false);
}
private File dir(String path, boolean bCreate) throws Exception {
File dir = new File(path);
if (dir.exists()) {
if (!dir.isDirectory()) {
throw new Exception(dir.getName() + "is not a directory !");
}
} else {
if (bCreate) { // 新建
if (!dir.mkdirs()) {
throw new Exception("can not create the directory \""
+ dir.getName() + "\"!");
}
}
}
return dir;
}
// 生成classpath字符串
private void classPath(File dir) {
classPath(dir, lib);
classPath = classPath.trim();
}
private void classPath(File dir, String parentPath) {
// 处理目录
if (dir.isDirectory()) {
File[] subs = dir.listFiles();
for (int i = 0, len = subs.length; i < len; i++) {
if (subs[i].isFile()) { // 文件
String name = subs[i].getName();
// 处理.jar文件
if (name.length() > fileType.length()
&& fileType.equals(name.substring(name.length()
- fileType.length(), name.length()))) {
classPath += parentPath + path(subs[i]) + " ";
continue;
}
}
if (subs[i].isDirectory()) { // 文件夹
classPath(subs[i], parentPath + path(subs[i]));
}
}
} else {
// 不是目录
System.out.println(dir.getPath() + dir.getName()
+ "is not a directory !");
}
}
// 文件路径
private String path(File f) {
return "/" + f.getName();
}
// 字符串 -- > 路径
@SuppressWarnings("unused")
private String path(String path) {
path = path.replaceAll("\\\\", "/");
if (!"/".equals(path.substring(0, 1))) {
path = "/" + path;
}
return path;
}
public void setLib(String lib) {
this.lib = lib;
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liuwei_blog/archive/2008/12/20/3567292.aspx
编译后打成jar包,拷贝到%ANT_HOME%\lib目录下,注意编译的时候需要导入ant的jar包,如果用ant打包就不需要导ant的jar包了,生成普通jar包的ant配置文件如下:
- <?xml version="1.0" encoding="GB2312" standalone="no"?>
- <project basedir="." default="usage" name="hibernate"> <!-- ====此处需要修改====工程名 -->
- <!-- 工程名,没有被引用,可以不改 -->
- <property name="project-name" value="hibernate"/> <!-- ====此处需要修改====.jar文件名 -->
- <property name="lib" value="lib"/> <!-- lib-->
- <property name="src" value="src"/> <!-- src-->
- <property name="tar" value="bin"/> <!-- bin -->
- <property name="jar-file-name" value="${project-name}.jar"/>
- <property name="main-class" value="demo.book.controler.Test"/> <!-- ====此处需要修改====main-class-->
- <path id="Third-Part Lib">
- <fileset dir="${lib}">
- <include name="**/*.jar"/>
- </fileset>
- </path>
- <target description="Build file usage info (default task)" name="usage">
- <echo message=" "/>
- <echo message=" ${project-name} "/>
- <echo message="-------------------------------------------------------"/>
- <echo message=" Available Targets:"/>
- <echo message=" compile - Compiles the source code"/>
- <echo message=" clean - Delete class files and .jar file"/>
- <echo message=" jar - Generate an .jar for source code"/>
- <echo message=" run - Execute Main-Class"/>
- <echo message="-------------------------------------------------------"/>
- </target>
- <target name="prepare">
- <mkdir dir="${tar}"/>
- </target>
- <target name="clean">
- <delete dir="${tar}"/>
- <delete file="${jar-file-name}"/>
- </target>
- <target name="copy-res">
- <copy todir="${tar}">
- <fileset dir="${src}">
- <exclude name="**/*.java"/>
- </fileset>
- </copy>
- </target>
- <target depends="clean,prepare,copy-res" name="compile">
- <javac debug="true" deprecation="true" destdir="${tar}" failonerror="true" srcdir="${src}">
- <classpath refid="Third-Part Lib"/>
- </javac>
- </target>
- <!--
- <target name="run" depends="jar">
- <java jar="${jar-file-name}" fork="true" maxmemory="256m"/>
- </target>
- -->
- <!-- 注意:classpath="${tar}" 一定要加上,否则会报"java.lang.NoClassDefFoundError"的错误!-->
- <target depends="compile" name="run">
- <java classname="${main-class}" classpath="${tar}" fork="true" maxmemory="256m">
- <classpath refid="Third-Part Lib"/>
- </java>
- </target>
- <target depends="compile" name="jar">
- <jar basedir="${tar}" destfile="${jar-file-name}">
- <manifest>
- <attribute name="Main-Class" value="${main-class}"/>
- <attribute name="Class-Path" value=""/>
- </manifest>
- </jar>
- </target>
- </project>
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<project basedir="." default="usage" name="hibernate"> <!-- ====此处需要修改====工程名 -->
<!-- 工程名,没有被引用,可以不改 -->
<property name="project-name" value="hibernate"/> <!-- ====此处需要修改====.jar文件名 -->
<property name="lib" value="lib"/> <!-- lib-->
<property name="src" value="src"/> <!-- src-->
<property name="tar" value="bin"/> <!-- bin -->
<property name="jar-file-name" value="${project-name}.jar"/>
<property name="main-class" value="demo.book.controler.Test"/> <!-- ====此处需要修改====main-class-->
<path id="Third-Part Lib">
<fileset dir="${lib}">
<include name="**/*.jar"/>
</fileset>
</path>
<target description="Build file usage info (default task)" name="usage">
<echo message=" "/>
<echo message=" ${project-name} "/>
<echo message="-------------------------------------------------------"/>
<echo message=" Available Targets:"/>
<echo message=" compile - Compiles the source code"/>
<echo message=" clean - Delete class files and .jar file"/>
<echo message=" jar - Generate an .jar for source code"/>
<echo message=" run - Execute Main-Class"/>
<echo message="-------------------------------------------------------"/>
</target>
<target name="prepare">
<mkdir dir="${tar}"/>
</target>
<target name="clean">
<delete dir="${tar}"/>
<delete file="${jar-file-name}"/>
</target>
<target name="copy-res">
<copy todir="${tar}">
<fileset dir="${src}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target depends="clean,prepare,copy-res" name="compile">
<javac debug="true" deprecation="true" destdir="${tar}" failonerror="true" srcdir="${src}">
<classpath refid="Third-Part Lib"/>
</javac>
</target>
<!--
<target name="run" depends="jar">
<java jar="${jar-file-name}" fork="true" maxmemory="256m"/>
</target>
-->
<!-- 注意:classpath="${tar}" 一定要加上,否则会报"java.lang.NoClassDefFoundError"的错误!-->
<target depends="compile" name="run">
<java classname="${main-class}" classpath="${tar}" fork="true" maxmemory="256m">
<classpath refid="Third-Part Lib"/>
</java>
</target>
<target depends="compile" name="jar">
<jar basedir="${tar}" destfile="${jar-file-name}">
<manifest>
<attribute name="Main-Class" value="${main-class}"/>
<attribute name="Class-Path" value=""/>
</manifest>
</jar>
</target>
</project>
4.生成可执行jar包的ant配置文件如下:
- <?xml version="1.0" encoding="GB2312" standalone="no"?>
- <project basedir="." default="usage" name="hibernate"> <!-- ====此处需要修改====工程名 -->
- <!-- 工程名,没有被引用,可以不改 -->
- <property name="project-name" value="hibernate"/> <!-- ====此处需要修改====.jar文件名 -->
- <property name="lib" value="lib"/> <!-- lib-->
- <property name="src" value="src"/> <!-- src-->
- <property name="tar" value="bin"/> <!-- bin -->
- <property name="jar-file-name" value="${project-name}.jar"/>
- <property name="main-class" value="demo.book.controler.Test"/> <!-- ====此处需要修改====main-class-->
- <path id="Third-Part Lib">
- <fileset dir="${lib}">
- <include name="**/*.jar"/>
- </fileset>
- </path>
- <target description="Build file usage info (default task)" name="usage">
- <echo message=" "/>
- <echo message=" ${project-name} "/>
- <echo message="-------------------------------------------------------"/>
- <echo message=" Available Targets:"/>
- <echo message=" compile - Compiles the source code"/>
- <echo message=" clean - Delete class files and .jar file"/>
- <echo message=" jar - Generate an .jar for source code"/>
- <echo message=" run - Execute Main-Class"/>
- <echo message="-------------------------------------------------------"/>
- </target>
- <target name="prepare">
- <mkdir dir="${tar}"/>
- </target>
- <target name="clean">
- <delete dir="${tar}"/>
- <delete file="${jar-file-name}"/>
- </target>
- <target name="copy-res">
- <copy todir="${tar}">
- <fileset dir="${src}">
- <exclude name="**/*.java"/>
- </fileset>
- </copy>
- </target>
- <target depends="clean,prepare,copy-res" name="compile">
- <javac debug="true" deprecation="true" destdir="${tar}" failonerror="true" srcdir="${src}">
- <classpath refid="Third-Part Lib"/>
- </javac>
- </target>
- <!--
- <target name="run" depends="jar">
- <java jar="${jar-file-name}" fork="true" maxmemory="256m"/>
- </target>
- -->
- <!-- 注意:classpath="${tar}" 一定要加上,否则会报"java.lang.NoClassDefFoundError"的错误!-->
- <target depends="compile" name="run">
- <java classname="${main-class}" classpath="${tar}" fork="true" maxmemory="256m">
- <classpath refid="Third-Part Lib"/>
- </java>
- </target>
- <!-- 自定义任务,创建并赋值变量class-path -->
- <taskdef name="jarcp" classname="personal.lw.util.AntUtil"/>
- <target name="class-path">
- <jarcp lib="${lib}"/>
- </target>
- <target depends="compile,class-path" name="jar">
- <jar basedir="${tar}" destfile="${jar-file-name}">
- <manifest>
- <attribute name="Main-Class" value="${main-class}"/>
- <attribute name="Class-Path" value="${class-path}"/>
- </manifest>
- </jar>
- </target>
- </project>
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<project basedir="." default="usage" name="hibernate"> <!-- ====此处需要修改====工程名 -->
<!-- 工程名,没有被引用,可以不改 -->
<property name="project-name" value="hibernate"/> <!-- ====此处需要修改====.jar文件名 -->
<property name="lib" value="lib"/> <!-- lib-->
<property name="src" value="src"/> <!-- src-->
<property name="tar" value="bin"/> <!-- bin -->
<property name="jar-file-name" value="${project-name}.jar"/>
<property name="main-class" value="demo.book.controler.Test"/> <!-- ====此处需要修改====main-class-->
<path id="Third-Part Lib">
<fileset dir="${lib}">
<include name="**/*.jar"/>
</fileset>
</path>
<target description="Build file usage info (default task)" name="usage">
<echo message=" "/>
<echo message=" ${project-name} "/>
<echo message="-------------------------------------------------------"/>
<echo message=" Available Targets:"/>
<echo message=" compile - Compiles the source code"/>
<echo message=" clean - Delete class files and .jar file"/>
<echo message=" jar - Generate an .jar for source code"/>
<echo message=" run - Execute Main-Class"/>
<echo message="-------------------------------------------------------"/>
</target>
<target name="prepare">
<mkdir dir="${tar}"/>
</target>
<target name="clean">
<delete dir="${tar}"/>
<delete file="${jar-file-name}"/>
</target>
<target name="copy-res">
<copy todir="${tar}">
<fileset dir="${src}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target depends="clean,prepare,copy-res" name="compile">
<javac debug="true" deprecation="true" destdir="${tar}" failonerror="true" srcdir="${src}">
<classpath refid="Third-Part Lib"/>
</javac>
</target>
<!--
<target name="run" depends="jar">
<java jar="${jar-file-name}" fork="true" maxmemory="256m"/>
</target>
-->
<!-- 注意:classpath="${tar}" 一定要加上,否则会报"java.lang.NoClassDefFoundError"的错误!-->
<target depends="compile" name="run">
<java classname="${main-class}" classpath="${tar}" fork="true" maxmemory="256m">
<classpath refid="Third-Part Lib"/>
</java>
</target>
<!-- 自定义任务,创建并赋值变量class-path -->
<taskdef name="jarcp" classname="personal.lw.util.AntUtil"/>
<target name="class-path">
<jarcp lib="${lib}"/>
</target>
<target depends="compile,class-path" name="jar">
<jar basedir="${tar}" destfile="${jar-file-name}">
<manifest>
<attribute name="Main-Class" value="${main-class}"/>
<attribute name="Class-Path" value="${class-path}"/>
</manifest>
</jar>
</target>
</project>
只比上一个多了一个自定义任务。
(完) ^_^
Ant自带了大量的任务(Task),在网上也有大量的任务可用,可是如果你面对的是别人根本不会想到的问题,怎么办呢?其实,只要花一点点功夫就可以编写出自己的任务出来。我开始也没想到会这样简单(做嵌套任务碰到一点问题),由此可见Ant的结构设计是相当优秀的。
假设我们需要显示任务执行各花了多少时间,写一个TimerTask
起步:覆盖org.apache.tools.ant.Task的execute方法
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
publicclass TimerTask extends Task {
publicvoid execute() throws BuildException {
System.out.println("I am a timer");
}
}
注意,编译时ant.jar必须在Classpath上。
简单起见,假设Java源文件,类文件在同一目录下,在此目录再写一个build.XML文件:
<?xml version="1.0" ?>
<projectname="testTimer"default="test" basedir=".">
<taskdefname="timer" classname="TimerTask" classpath="."/>
<targetname="test">
<timer/>
</target>
</project>
打开Dos窗口,到此目录,运行ant
够简单吧!如果类路径比这复杂或者在jar文件中,设置<taskdef>的classpath属性就行了。
继续:设置属性
假设我们想添加一个action属性,在Java文件中:
private String action;
….
public void execute() throws BuildException {
if (action.equals(“init”)) {
…
}
…
}
public String getAction() {
return action;
}
public void setAction(String string) {
action = string;
}
在xml文件中:
<timer action=”init” />
使用Project保存中间结果
对于这个任务来讲,必须把时间值保存起来,比较合适的就是org.apache.tools.ant.Project了,Project对象生命期是整个Build,并且可以通过setProperty, getProperty等方法保存/获取值。
publicvoid execute() throws BuildException {
if (getOwningTarget() ==null)
return;
Project proj = getOwningTarget().getProject();
…
// can do smt with proj now
}
晋级:嵌套任务
如果我们想要在Timer下面再嵌套子任务(好像没有这个必要 :-):
<timer action=”init” >
<foo />
</timer>
那我们首先只需要写一个简单的FooTask,然后在build.xml加上<foo>的定义:
<taskdefname="timer" classname="TimerTask" classpath="."/>
<taskdefname="foo" classname="FooTask" classpath="."/>
然后给TimerTask添加一个方法:
public void addFoo(FooTask foo) {
}
注意:addXXX的XXX由<taskdef>中的name决定,Ant会利用Java Reflection去找;类型必须是具体的类型FooTask,不能是Task。
结束:全部代码:
(问什么不能带附件?)
TimerTask.Java:
import java.util.*;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.BuildException;
/**
*TimerTask.java
*<p>Copyright:Copyright (c)2003 你可以对本程序随意修改,复制,使用,但请保留这里注释声明!!!</p>
*@author 李尚强blundblade@sina.com
*/
publicclass TimerTask extends Task {
private List fooList =new ArrayList();
private String action =""; //init, print
privatestatic final String TIME_PROPERTY_INTERNAL ="timer.msecs";
privatestatic final String TIME_PROPERTY_NAME ="timer.passed";
publicvoid execute() throws BuildException {
System.out.println("I am a timer");
System.out.println("but there are so many foos: " + fooList);
if (this.getOwningTarget() ==null)
return;
Project proj = this.getOwningTarget().getProject();
String strTime = proj.getProperty(TIME_PROPERTY_INTERNAL);
try {
long currMSecs = System.currentTimeMillis();
if (action.equals("print")){
if (strTime ==null)
proj.setProperty(TIME_PROPERTY_NAME,"Timer not initilized");
else {
long startMSecs = Long.parseLong(strTime);
long passedSecs = currMSecs - startMSecs;
int minutes = (int) ( passedSecs * 1.0 / (1000 * 60 * 60) );
int hours = minutes / 60;
minutes = minutes % 60;
strTime = hours + " hours " + minutes + " minutes";
proj.setProperty(TIME_PROPERTY_NAME, strTime);
}
}
elseif (action.equals("init")) {
proj.setProperty(TIME_PROPERTY_INTERNAL, Long.toString(currMSecs));
}
}
catch (NumberFormatException nfe) {
thrownew BuildException(nfe.getMessage());
}
}
publicvoid addFoo(FooTask foo){
fooList.add(foo);
}
/**
*@return
*/
public String getAction() {
return action;
}
/**
*@param string
*/
publicvoid setAction(String string) {
action = string;
}
}
FooTask.Java:
/*
* Created on 2004-4-17
*
*/
import org.apache.tools.ant.Task;
/**
* FooTask.java
* <p>Copyright: Copyright (c) 2003 你可以对本程序随意修改,复制,使用,但请保留这里注释声明!!!</p>
* @author李尚强 blundblade@sina.com
*/
public class FooTask extends Task {
private String name ="";
/**
* @return
*/
public String getName() {
return name;
}
/**
* @paramstring
*/
public void setName(String string) {
name = string;
}
public String toString() {
return name;
}
}
build.XML:
<?xml version="1.0" ?>
<project name="testTimer" default="test" basedir=".">
<taskdef name="timer" classname="TimerTask"classpath="."/>
<taskdef name="foo" classname="FooTask"classpath="."/>
<target name="test">
<timer action="init">
<foo name="F1" />
<foo name="F2" />
<foo name="F3" />
<foo name="F4" />
</timer>
<!-- You can do some long-time work here -->
<timer action="print" />
<echo message="You have use time :${timer.passed}"/>
</target>
</project>