Automating Compilation with Ant


You get tired of typing javac and java commands.


Use the Ant program to direct your compilations.


The intricacies of makefiles and their importabilities have led to the development of a pure-Java solution for automating the build process. Ant is free software; it is available in source form or ready-to-run from the Apache Foundation’s Jakarta project web site, at Like make, Ant uses a file or files -- written in XML -- listing what to do and, if necessary, how to do it. These rules are intended to be platform-independent, though you can of course write platform-specific recipes if necessary.

To use Ant you must create a 15-30 line file specifying various options. This file should be called build.xml ; if you call it anything else, you’ll have to give a special command-line arguments every time you run Ant. Example 1-1 shows the build script used to build the files in the starting directory. See Section 21.1 for discussion of the XML syntax. For now, note that the <!- - tag begins an XML comment, which extends to the - -> tag.

Example 1-1. Ant example file (build.xml)

<project name="Java Cookbook Examples" default="compile" basedir=".">

  <!-- set global properties for this build -->
  <property name="src" value="."/>
  <property name="build" value="build"/>
  <!-- Specify the compiler to use. 
    Using jikes is supported but requires rt.jar in classpath. -->
  <property name="build.compiler" value="modern"/>

  <target name="init">
    <!-- Create the time stamp -->
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>

  <!-- specify what to compile. This builds everything -->
  <target name="compile" depends="init">

    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}"


When you run Ant, it produces a reasonable amount of notification as it goes, similar to make :

$ ant  compile
Buildfile: build.xml
Project base dir set to: /home/ian/javasrc/starting
Executing Target: init
Executing Target: compile
Compiling 19 source files to /home/ian/javasrc/starting/build
Performing a Modern Compile
Copying 22 support files to /home/ian/javasrc/starting/build
Completed in 8 seconds

See Also

Make Versus Ant.

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.