Automating Compilation with Ant

Problem

You get tired of typing javac and java commands.

Solution

Use the Ant program to direct your compilations.

Discussion

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 http://jakarta.apache.org/ant/. 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 -->
    <tstamp/>
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>
  </target>

  <!-- 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}"
          classpath="../com-darwinsys-util.jar"/>
  </target>

</project>

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.