Ant - Build Files


Typically, Ant's build file, build.xml should live in the project's base directory. Although you are free to use other file names or place the build file in some other location.

For this exercise, create a file called build.xml anywhere in your computer.

<?xml version="1.0"?>
   <project name="Hello World Project" default="info">
   <target name="info">
      <echo>Hello World - Welcome to Apache Ant!</echo>

Please note that there should be no blank lines or whitespaces before the xml declaration. If you do, this may cause an error message when running the ant build - The processing instruction target matching "[xX][mM][lL]" is not allowed.

All buildfiles require the project element and at least one target element.

The XML element project has three attributes :

nameThe Name of the project. (Optional)
defaultThe default target for the build script. A project may contain any number of targets. This attribute specifies which target should be considered as the default. (Mandatory)
basedirThe base directory (or) the root folder for the project. (Optional)

A target is a collection of tasks that you want to run as one unit. In our example, we have a simple target to provide an informational message to the user.

Targets can have dependencies on other targets. For example, a deploy target may have a dependency on the package target, and the package target may have a dependency on the compile target and so forth. Dependencies are denoted using the depends attribute. For example:

<target name="deploy" depends="package">
<target name="package" depends="clean,compile">
<target name="clean" >
<target name="compile" >

The target element has the following attributes:

nameThe name of the target (Required)
dependsComma separated list of all targets that this target depends on. (Optional)
descriptionA short description of the target. (optional)
ifAllows the execution of a target based on the trueness of a conditional attribute. (optional)
unlessAdds the target to the dependency list of the specified Extension Point. An Extension Point is similar to a target, but it does not have any tasks. (Optional)

The echo task in the above example is a trivial task that prints a message. In our example, it prints the Hello World message.

To run the ant build file, open up command prompt and navigate to the folder where the build.xml resides, and type ant info. You could also just type ant instead. Both will work, because info is the default target in the build file. You should see the following output:

Buildfile: C:\build.xml

     [echo] Hello World - Welcome to Apache Ant!

Total time: 0 seconds