ant脚本结构
ant使用XML格式的配置文件,默认的名称是build.xml。配置文件的根节点是project,且project节点至少含有一个target子节点,先上代码:
1: <project name="MyProject" default="dist" basedir="."> 2: </project>
属性name表示项目的名称,default是在不指定任务时默认执行的任务,basedir用于从相对路径计算出绝对路径,如果没有设置,默认是配置文件(XML)所在的目录。
定义变量使用的是property,格式如下:
1: <property name="src" location="src"/> 2: <property name="src" value="value"/>
其中name是变量的名字,如果是location,该变量的值是location对应值的文件的路径;如果location已经是绝对路径则直接赋值给name对应的变量,如果location是相对目录,则将项目中basedir与该路径连接并赋值给name对应的变量。
完整的buildfile示例
1: <project name="MyProject" default="dist" basedir="."> 2: <description> 3: simple example build file 4: </description> 5: <!-- set global properties for this build --> 6: <property name="src" location="src"/> 7: <property name="build" location="build"/> 8: <property name="dist" location="dist"/> 9: 10: <target name="init"> 11: <!-- Create the time stamp --> 12: <tstamp/> 13: <!-- Create the build directory structure used by compile --> 14: <mkdir dir="${build}"/> 15: </target> 16: 17: <target name="compile" depends="init" 18: description="compile the source " > 19: <!-- Compile the java code from ${src} into ${build} --> 20: <javac srcdir="${src}" destdir="${build}"/> 21: </target> 22: 23: <target name="dist" depends="compile" 24: description="generate the distribution" > 25: <!-- Create the distribution directory --> 26: <mkdir dir="${dist}/lib"/> 27: 28: <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file --> 29: <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/> 30: </target> 31: 32: <target name="clean" 33: description="clean up" > 34: <!-- Delete the ${build} and ${dist} directory trees --> 35: <delete dir="${build}"/> 36: <delete dir="${dist}"/> 37: </target> 38: </project>
如何打jar包,如何把外部的jar包一起打包到目标jar中?
1: <path id="build.classpath"> 2: <fileset dir="lib"> 3: <include name="*.jar"/> 4: </fileset> 5: </path> 6: <manifestclasspath property="manifest.classpath" jarfile="ExceltoXML.jar"> 7: <classpath refid="build.classpath" /> 8: </manifestclasspath> 9: <target name="jar" depends="compile"> 10: <jar destfile="ExceltoXML.jar"> 11: <fileset dir="build/classes"/> 12: <fileset dir="lib" /> 13: <manifest> 14: <attribute name="Main-Class" value="xgh.ExceltoXML" /> 15: <attribute name="Class-Path" value="${manifest.classpath}" /> 16: </manifest> 17: </jar> 18: </target>
说明:manifestclasspath用来设置目标jar运行时候的环境变量,否则将会出现class not found的错误。