How to compile a Java program with Ant

While I'm digging around through Ant build scripts today, here's a sample Ant target I created that demonstrates how to compile a Java program, while also showing a few other things, including how to exclude your JUnit tests during the compile process.

This particular script happened to be used for building a Swing application, but it can really be used to build any Java application, command-line based or other.

Here's the source code for my Ant compile target:

<target name="compile" depends="clean-classes-dir">
  <javac destdir="classes" source="1.5" >
    <src path="src"/>
    <exclude name="**/Test*.java"/>
    <classpath refid="class.path"/>
  <copy todir="classes">
    <fileset dir="src">
      <include name="**/*.gif"/>
      <include name="**/*.jpg"/>
      <include name="**/*.png"/>


Here's a brief description of what this Ant target does:

  1. The first part of the script runs the Ant javac task.
  2. This task compiles all the files found in the src directory, excluding all files matching the naming patter Test*.java. By convention, I named all my unit test classes this way, so I am able to exclude them in the compiling process.
  3. When compiling, I set the classpath using the class.path variable, which I created earlier in my build script.
  4. After the javac task executes successfully, I copy a bunch of image files from the src directory structure to the classes folder structure. (This is a collection of images that are used by my application.)

Building the classpath

I mentioned that earlier in my build script I created the variable named class.path. For the purpose of completeness, I thought I better include the target I created that builds this classpath variable. Here's the source code for that part of my build process:

<path id="class.path">
  <fileset dir="lib">
    <include name="**/*.jar"/>
    <include name="**/*.zip"/>

As you can see, this segment of code builds a variable named class.path based on all the jar and zip files that are in my project's lib folder.