最近换公司了,项目中有用到ant作为项目编译打包工具,所以觉得有必要去学习了解一下。
Ant是一强大的构建工具,使用ant首先需要配置安装jdk;然后下载安装Ant。下载地址:http://mirrors.hust.edu.cn/apache//ant/binaries/apache-ant-1.9.9-bin.zip。下载好之后就是配置环境变量ANT_HOME:E:\Java\apache-ant-1.9.9,path:%ANT_HOME%/bin,classpath:%ANT_HOME%\lib 配置好之后在doc窗口中执行ant命令,看是否安装成功。
C:\Users\Administrator>ant
Buildfile: build.xml does not exist!
Build failed
如果出现这个就是安装成功。
通过Ant,我们可以编译,打包,复制,运行java文件。下面是一个小示例。
创建一个文件目录\src\main\java,新建一个java文件:HelloWorld.java,与src平级目录新建一个build.xml文件。
HelloWorld.java
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="HelloWorld" default="run" basedir=".">
<property name="src" value="src"/>
<property name="dest" value="classes"/>
<property name="hello_jar" value="hello.jar"/>
<target name="init">
<mkdir dir="${dest}"/>
</target>
<target name="compile" depends="init">
<javac srcdir="${src}" destdir="${dest}"/>
</target>
<target name="build" depends="compile">
<jar jarfile="${hello_jar}" basedir="${dest}"/>
</target>
<target name="run" depends="build">
<java classname="HelloWorld" classpath="${hello_jar}"/>
</target>
</project>
运行
C:\Users\Administrator>ant F:\学习资料\build.xml
Buildfile: build.xml does not exist!
Build failed
C:\Users\Administrator>ant -f F:\学习资料\build.xml
Buildfile: F:\学习资料\build.xml
init:
compile:
[javac] F:\学习资料\build.xml:10: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable
builds
[javac] Compiling 1 source file to F:\学习资料\classes
build:
[jar] Building jar: F:\学习资料\hello.jar
run:
[java] Hello World!
BUILD SUCCESSFUL
Total time: 1 second
可以看到目录中生成了一个jar文件,运行结果也输出了打印信息。