Ant is free and open source build tool, written in Java, helps in automating the entire build process of a Java development project.
- Ant uses XML build files.
- By default, Ant looks for a build file named build.xml.
- The build file contains information about how to build a particular project.
- Each project contains multiple targets like creating directory, compiling source codes.
- Target can depend on other targets.
- Targets contain tasks.
- Behind each task is a Java class that performs the described work.
To install Ant follow the steps given below.
- Download the latest Ant distribution.
- Extract it (my location is E:\apache-ant-1.7.1)
- Set the following system variables
- ANT_HOME =E:\apache-ant-1.7.1
- PATH = %ANT_HOME%\bin
To make sure the installation is proper, go to command prompt and execute the command "ant - version", you will see the installed ant version.
In this example you will see how to compile a java program and compress it into a .jar file using Ant build file. The following listing shows the build.xml file.
<?xml version="1.0" ?> <project name="Hello World" default="compress"> <target name="compile"> <javac srcdir="."/> <echo> Compilation Complete! </echo> </target> <target name="compress" depends="compile"> <jar destfile="HelloWorld.jar" basedir="." includes="*.class" /> <echo> Building .jar file Complete! </echo> </target> </project>
- The <project> element is the root element in Ant build files. The name attribute of the project element indicates the project name. Each project element can contain multiple <target> elements.
- A target represents a single stage in the build process. A build process can have multiple targets. Here we have two targets compile and compress.
- The default attribute of project element indicates the default target to be executed. Here the default target is compress.
- When you see the compress target, it in turn depends on the compile target, that is indicated by the depends attribute. So the compile target will be executed first.
- The compile target has two task elements <javac> and <echo>. The javac task is used to compile the java files. The attribute srcdir="." indicates all the java files in the current directory. Echo task is used to display message on the console.
- The compress target also performs two tasks, first the <jar> element as the name indicates, is used to build the jar file. The attributes destfile="HelloWorld.jar" , basedir="." and includes="*.class" indicates all the .class files in the current directory should be compressed into HelloWorld.jar file. Later the echo task is used to display the success message on the console.
To run the build.xml file, open the command prompt, go to the example directory, type the command "ant". You will see the following information.
You can download the build file here.
Build file : Download
Project : Download