Home » Core Java » apache » ANT » Apache Ant Tutorial for Beginners

About David Guinivere

David Guinivere

David graduated from University of California, Santa Cruz with a Bachelor’s degree in Information Science. He has been actively working with Java since the days of J2SE 1.2 in 1998. His work has largely involved integrating Java and SQL. He has worked on a wide range of projects including e-commerce, CRM, Molecular Diagnostic, and Video applications. As a freelance developer he is actively studying Big Data, Cloud and Web Development.

Apache Ant Tutorial for Beginners

1. Introduction

This tutorial explains why Ant was created and its’ advantages over other build tools. This tutorial also covers the installation of Ant and what goes into an Ant project. In this tutorial, a sample project is set up. The Ant build file, for the sample project, is explored along with a discussion of how Ant is used to build the project.

The tutorial ends with a link to download the entire project including source code, data file, and Ant build file.

Tip
You may skip the introductory part and jump directly to the Tutorial below.

2. Overview

Ant is a popular build tool and is included with most modern IDEs such as IntelliJ IDEA, Eclipse, and NetBeans. Since Ant is open source, users can extend the product by creating their own “antlibs”. (See the documentation on the Ant website ant.apache.org)

ANT (“Another Neat Tool”) is built using Java, mainly for building, testing and deploying Java applications. It was originally part of the Apache Tomcat code base and was released as a standalone product in July 2000.

Ant uses XML files for instructions to build Projects. Build tools such as make, gnumake, and jam are shell based tools. Meaning once the dependencies are determined, each task is completed by issuing shell commands, which are limited to the particular OS where the project is being built. Ant avoids this limitation by using Java objects to execute tasks. However, if you need or want to use a shell command, Ant has an task to allow the execution of OS shell commands.

Since many applications use a polyglot (many languages) model Ant comes with tasks for compiling C, C++, C#, and other languages.

3. Installation

3.1. Ubuntu

Use the apt-get install ant command to install Ant on Ubuntu. For other distributions, please check the documentation of your vendor.

3.2. Windows

a. Download the binary from ant.apache.org
NOTE: Download the 1.10.x version if you are running Java 8 (recommended). Download the 1.9.x version if you are running Java 5.

b. Unzip the binary into a directory of your choice. For this tutorial, the Ant binary was unzipped into C:\Ant

c. Set the ANT_HOME environment variable to the directory where Ant was unzipped. For this tutorial: ANT_HOME=C:\Ant

Set ANT_HOME System variable

Set ANT_HOME System variable

d. Edit the PATH system variable. Append “;%ANT_HOME%\bin” (without the quotes).

Append to the PATH User variable

Append to the PATH User variable

3.3. Testing the Installation

To test your Ant installation:
a. Open a command window and navigate to any directory which DOES NOT contain a build.xml file.

b. Issue the command: ant

You should receive the error message:
Buildfile: build.xml does not exist!
Build failed

Buiil Failed error message when installed

Error message appear if installed properly

4. Anatomy of an Ant Project

As mentioned above Ant receives its instructions on how to build a particular project from an XML file. The default Ant project file is build.xml

4.1. XML Declaration

Since the Ant build file is an XML file it begins with the typical declaration of an XML file with its version:

<?xml version="1.0" encoding="UTF-8"?>

4.2. Project Tag

The <project> element is the outer most element in the Ant build file. It is a “container” for all of the properties, tasks, and targets that define the Ant project contained in the build file.

<project name="MyApplication" default="compile" basedir="." >>

The <project> element has three attributes.
1. name: Set the name of the project contained in this file.
2. default: Set the default target to be executed by ant file.
3. basedir: Set the base directory (i.e.: root folder) of this project.
In this case “.” means the current directory. If this is omitted the parent directory of the build file will be used.

4.3. Tasks

Tasks are predefined individual units of work. Each task uses attributes set to values in order to customize the results of executing the task. Below are some examples of how set some of the <delete> task attributes to get different results:

<!--  Deletes the file /lib/foo.jar -->
 <delete file="/lib/foo.jar"/>

<!-- Deletes all files with the extension .txt from the current directory and any subdirectories -->
 <delete>
    <fileset dir="." includes="**/*.txt"/>
  </delete>

<!--  Deletes the build directory, including all of the files and subdirectories -->
 <delete dir="build"/>

<!-- Deletes the build directory, including all of the files and subdirectories-->
<!—Same as above -->
  <delete includeEmptyDirs="true">
    <fileset dir="build"/>
  </delete>

<!-- Deletes all files and subdirectories of build, but leave the build directory -->
  <delete includeEmptyDirs="false">
    <fileset dir="build"/>
  </delete>

Ant comes with over 150 predefined tasks. The predefined tasks can be broken down into the following categories:

Archive Tasks
Audit/Coverage Tasks
Compile Tasks
Deployment Tasks
Documentation Tasks
EJB Tasks
Execution Tasks
File Tasks
Java2 Extensions Tasks
Logging Tasks
Mail Tasks
Miscellaneous Tasks
Pre-process Tasks
Property Tasks
Remote Tasks
SCM Tasks
Testing Tasks

The Apache Ant User manual provides tables for each of the above categories showing the task name, a brief synopsis of what the task does and a link to the complete documentation. See Ant User Manual ( https://ant.apache.org/manual/index.html ) –> Table of Contents –> Ant Tasks –> Overview of Apache Ant Tasks.

4.4. Properties

Properties can be thought of as global constants that are immutable. However, they can be used throughout the project. Properties simply associate names with values. They are tasks which do not need to be enclosed within a <target> element. There is no limit to the number of <property> elements that can be defined.

The most popular syntax for defining a <property> element takes one of these forms:

<!-- Sets the property foo to the value "bar" -->
  <property name="foo" value="bar"/>

<!-- Sets the property foo to the value "bar" (Same as above) -->
  <property name="foo">bar</property>

<!-- Reads a set of properties from a file called "myproperties" -->
  <property file="myproperties"/>

<!-- Reads a set of properties from "http://www.awebsite.com/props/build.properties" -->
  <property url="http://www.mysite.com/props/build.properties"/>

To retrieve the value associated with a particular property; surround the property name with ${ } for example from the examples above ${foo} would expand to bar

Ant provides a number of built in properties (taken from the Ant User Manual):

basedirthe absolute path of the project’s basedir (as set with the basedir attribute of <<project>).
ant.filethe absolute path of the buildfile.
ant.versionthe version of Ant ant.project.name the name of the project that is currently executing; it is set in the name attribute of <project>
ant.project.default-targetthe name of the currently executing project’s default target; it is set via the default attribute of <project>
ant.project.invoked-targetsa comma separated list of the targets that have been specified on the command line (the IDE, an task …) when invoking the current project. This property is set properly when the first target is executed. If you use it in the implicit target (directly under the tag) the list will be empty if no target has been specified while it will contain the project’s default target in this case for tasks nested into targets.
ant.java.versionthe JVM version Ant detected; currently it can hold the values “9”, “1.8”, “1.7”, “1.6”, “1.5”, “1.4”, “1.3” and “1.2”.
ant.core.libthe absolute path of the ant.jar file.

4.5. Targets

Target elements are user defined containers of tasks used to bring the build process to a known state. A powerful feature of targets is the depends attribute used to ensure targets are executed in the desired order.

For example, given the following targets:

<target name="init" />
<target name="clean" depends="init" />
<target name="compile" depends="clean" />
<target name="manifest" depends="compile" />
<target name="buildJar" depends="manifest,compile,clean,init" />

If the buildJar target is executed; from the depends attribute the expected order of target execution might be: manifest –> compile –> clean –> init before executing the buildJar target, which is exactly backwards from the desired order (since it makes no sense to build the .jar file first, and perform the initialization task last). Fortunately when evaluating the order of targets to be executed, the depends attribute of the buildJar target depends on manifest, which depends on compile, which in turn depends on clean, which depends on init. Ant only executes a target once within a dependency chain so the targets are executed once and in the expected order.

4.6. Extension-Points

Extension-Points are targets without tasks. Introduced in Ant 1.8. Extension-points are executed from the command-line. The main purpose of extension-points is to execute the targets in its dependency list to bring the build process to the desired state.

<extension-point name="build_source" depends="compile"/>

5. Sample Project

Here is the build.xml file that builds the three .java files into the Using a Default Handler Java application adapted from my earlier article <a href=”https://examples.javacodegeeks.com/core-java/xml/xpath/java-xpath-using-sax-example/”Java XPath Using SAX Example.

Sample project structure

Structure of AntSample project

The root directory for the project is proj, and contains:

build.xmlThe Ant build file for this project
inventory.xmlThe XML data file used by the application after being copied to the classes directory (which is created during the build)
SaxParse.batBatch file to run the application

 

The src directory contains the three Java source files:

Computer.java
JavaSAXParse.javaMain class
MyHandler.java

Below is the Ant build file – build.xml.

<?xml version="1.0" encoding="UTF-8"?>

<!-- Project definition -->
<project name="AntSample" basedir="." default="compile">

    <!-- Define properties needed for build -->
    <property name="srcdir"  value="src"/>
    <property name="outdir"  value="classes"/>

    <!-- Clean target.  Delete the output directory. -->
    <target name="clean" >
          <delete dir="${outdir}" />
    </target>
	
    <!-- Init target.  Create the output directory. if it does not exist. -->
    <!-- Copy inventory.xml to $(outdir) -->
    <target name="init" depends="clean" >
          <mkdir dir="${outdir}" />
		  <copy file="${basedir}\inventory.xml" todir="${outdir}" />
    </target>

    <target name="compile" depends="init" >
          <javac srcdir="${srcdir}" destdir="${outdir}" />
    </target>
	
</project>

To build the project:
1. Open a Command Prompt
2. Navigate to the root directory \AntSample\proj
3. Issue the command: ant

To run the application:
1. Open a Command Prompt
2. Navigate to the root directory \AntSample\proj
3. Issue the command: SAXparse.bat

6. For More Information

For more information consult the Ant Use Manual.

A copy of the manual is included with the Ant download. If you installed Ant, then your copy can be found at %ANT_HOME%\manual\index.html.

An online copy can be found at https://ant.apache.org/manual/index.html

7. Project Download

Download the Ant sample project presented in this tutorial.

Download
You can download the full project for this tutorial here: AntSampleProject.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz