Home
Blog
Tech How To

Basic Ant Build File

Create The Project

An Ant build file is just an XML file which Ant reads to determin what to do. First thing you need to do is create a project. References to commands may be found here

  <project name="MyProject" default="dist" basedir=".">
    <description>
        simple example build file
    </description>
  </project>


Add The Targets

Next lets add the stubs for the actions we want to perform. In Ant these are called targets. We'll have 4 targets, init, compile, distribute, and clean up.

  <project name="MyProject" default="dist" basedir=".">
    <description>
        simple example build file
    </description>

    <target name="init">
    </target>

    <target name="compile">
    </target>

    <target name="dist">
    </target>

    <target name="clean">
    </target>

  </project>

Add The Tasks

Now that the targets are in place we simply need to add the right tasks. For example in the target "compile" we'll add some tasks to compile the source code into byte code.

One more thing we'll add 3 properties at the top. These are just name value pairs which can be used by the tasks.

  <project name="MyProject" default="dist" basedir=".">
      <description>
          simple example build file
      </description>
    <!-- set global properties for this build -->
    <property name="src" location="src"/>
    <property name="build" location="build"/>
    <property name="dist"  location="dist"/>

    <target name="init">
      <!-- Create the time stamp -->
      <tstamp/>
      <!-- Create the build directory structure used by compile -->
      <mkdir dir="${build}"/>
    </target>

    <target name="compile" depends="init"
          description="compile the source " >
      <!-- Compile the java code from ${src} into ${build} -->
      <javac srcdir="${src}" destdir="${build}"/>
    </target>

    <target name="dist" depends="compile"
          description="generate the distribution" >
      <!-- Create the distribution directory -->
      <mkdir dir="${dist}/lib"/>

      <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
      <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
    </target>

    <target name="clean"
          description="clean up" >
      <!-- Delete the ${build} and ${dist} directory trees -->
      <delete dir="${build}"/>
      <delete dir="${dist}"/>
    </target>
  </project>

Test The Build

Now run the dist task. If you are using a tool like IDEA or ECLIPSE you'll need to add the build file then run the task. On the command line you can run ant yourself

  $PATH_TO_ANT/bin/ant -f build.xml

Now check for your jar file under ./dist/lib/ Check out CrackingJars for more info on working with jar files