Tutorials     About     RSS
Tech and Media Labs

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"/>

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

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

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

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

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

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

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

        <javadoc sourcepath="${dir.src}" destdir="${dir.build.javadoc}"></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

Featured Videos

Thread Congestion in Java - Video Tutorial

Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC