Ant Java Build Script Example

Jakob Jenkov
Last update: 2015-08-26

In this tutorial I will show how to build a Java project with Ant. Ant does not come with any predefined targets for building Java projects, so you will have to write your own. However, having to rewrite Ant build scripts from scratch every time you start a new Java project is tedious. Therefore this text provides a simple Ant build script for Java projects which you can use as a template for your own build scripts (or as inspiration or whatever).

I won't explain the various parts of this build script. Most parts are (or will be) explained in their own texts in this Ant tutorial trail. There is no reason to repeat all that here.

Here is the example Ant build script:

<project name="MyProject" basedir=".">

    <property name="version">1.2.3</property>
    <property name="dir.src">src/main/java</property>
    <property name="dir.build">build</property>
    <property name="dir.build.classes">${dir.build}/classes</property>
    <property name="dir.build.javadoc">${dir.build}/javadoc</property>
    <property name="file.jar">${dir.build}/MyProject-${version}.jar</property>


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

    <target name="clean">
        <delete dir="${dir.build}"/>
    </target>


    <target name="init">
        <mkdir dir="${dir.build}"/>
        <mkdir dir="${dir.build.classes}"/>
    </target>


    <target name="compile" depends="init">
        <echo>Compiling Java source</echo>

        <javac classpathref="projectClasspath"
               srcdir="${dir.src}"
               destdir="${dir.build.classes}" />
    </target>

    <target name="jar" depends="compile">
        <echo>Making JAR file</echo>

        <jar basedir="${dir.build.classes}" file="${file.jar}" />
    </target>

    <target name="javadoc">
        <echo>Making JavaDoc from source</echo>

        <javadoc sourcepath="${dir.src}" destdir="${dir.build.javadoc}"></javadoc>
    </target>

</project>

Notice how the jar target depends on the compile target, and the compile target depends on the init target. That way you are sure that all your code has been compiled when you run the jar target.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next