Using Ant

Apache Ant is a free Java-based build tool and can be downloaded from Because Ant is Java-based, Ant build files can be compiled on any platform. Also, Ant is integrated into many Java IDEs, so you can get up and running quickly. Ant build files are XML files, usually named build.xml. Listing I.1 contains an example build file.

Listing I.1 Sample Ant Build File
<?xml version="1.0"?>
<project default="build" basedir=".">
 <property value="src"/>
 <property value="build"/>
 <target description="Deletes the class files">
 <fileset dir="${destdir}" includes="**/*.class"/>
 <target description="Compiles the source code">
 <javac srcdir="${srcdir}"
 <target depends="compile"
 description="Compiles the source code and creates a jar file">
 <jar jarfile="${basedir}/myjar.jar">
 <fileset dir="${destdir}" includes="**/*.class"/>
 <target depends="clean, build"
 description="Performs a clean build"/>

The sample Ant file almost describes itself. First, two properties are created to specify the srcdir and destdir directories. Properties can be referred to using the ${varName} syntax. The build file contains four targets: clean, compile, build, and rebuild. The compile target compiles all Java files in the source directory, putting the compiled class files in the destination directory. The clean target deletes all of these classes. The build target depends on the compile target, so running the build target automatically runs the compile target first. The build target packs all the compiled class files into a .jar file. Finally, the rebuild target does nothing by itself, but depends on the clean and build targets to perform a clean build. After you've got Ant installed, just open a command prompt in the directory of the build file and type in the target you want to execute, like this:

ant compile

This command loads the build.xml file in the current directory and executes the compile target. If you were to name no target, as in the following, the build target is executed because it's defined to be the default target in the build file:


Besides running Ant from the command line, Ant is also tightly integrated into many IDEs and text editors, such as JBuilder, jEdit, Eclipse, IDEA, and NetBeans. For example, in jEdit (see Screenshot I.1), the AntFarm plug-in enables you to browse Ant files, execute targets with the click of the mouse, and even send compile errors to jEdit's ErrorList plug-in so you can click on errors to go directly to the source of the compile error.

Screenshot I.1. Ant integration with jEdit 4.1: a popular, highly configurable open-source editor.

Java graphics infig01.gif

This Ant build file example really just scratches the surface for what Ant can do. There are lots of built-in Ant tasks and many more optional tasks, and you can even write your own tasks. You can see what all the available tasks are and get more information on using Ant at