Tuesday, 4 December 2012

Ant Build Tool


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.N)
  • Set the following system variables
  • ANT_HOME =E:\apache-ant-1.N
  • 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.
01.<?xml version="1.0" ?>
02.<project name="Hello World" default="compress">
03. 
04.<target name="compile">
05.<javac srcdir="."/>
06.<echo> Compilation Complete! </echo>
07.</target>
08. 
09.<target name="compress" depends="compile">
10.<jar destfile="HelloWorld.jar" basedir="." includes="*.class" />
11.<echo> Building .jar file Complete! </echo>
12.</target>
13. 
14.</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="." andincludes="*.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.