Tech and Media Labs
This site uses cookies to improve the user experience.

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="">build</property>
    <property name="">${}/classes</property>
    <property name="">${}/javadoc</property>
    <property name="file.jar">${}/MyProject-${version}.jar</property>

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

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

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

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

        <javac classpathref="projectClasspath"
               destdir="${}" />

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

        <jar basedir="${}" file="${file.jar}" />

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

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


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

Copyright  Jenkov Aps
Close TOC