newspaint

Documenting Problems That Were Difficult To Find The Answer To

A Basic Ant Build Script For Simple Java Projects

Here is a basic Apache Ant build script I use for taking one or more source Java files and associated jars and bundling them all into a single jar with a main class.

I have the following directory structure:

|--build.xml
|--src\
|  +--MyMainClass.java
|  +--OtherClass.java
+--lib\
   +--dependency.jar

When I run ant jar using the below build.xml it will then create new directories:

|--build
|  +--classes
|     +--MyMainClass.class
|     +--OtherClass.class
+--jar
   +--myproject.jar

Running ant clean will remove the newly created folders build/ and jar/.

This tutorial is also very helpful.

<project name="myproject">
  <property name="src.dir"     value="src"/>

  <property name="build.dir"   value="build"/>
  <property name="classes.dir" value="${build.dir}/classes"/>
  <property name="jar.dir"     value="jar"/>
  <property name="jar.file"    value="${jar.dir}/${ant.project.name}.jar" />

  <property name="lib.dir"     value="lib" />

  <property name="main-class"  value="MyMainClass" />

  <path id="classpath">
    <fileset dir="${lib.dir}" includes="**/*.jar" />
  </path>


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

  <target name="compile">
    <mkdir dir="${classes.dir}" />
    <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath" />
  </target>

  <target name="jar" depends="compile">
    <mkdir dir="${jar.dir}" />
    <jar destfile="${jar.file}" basedir="${build.dir}">
      <manifest>
        <attribute name="Main-Class" value="${main-class}" />
      </manifest>
      <fileset dir="${classes.dir}" includes="**/*.class" />
      <fileset dir="${src.dir}" includes="**/*.java" />
      <zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
    </jar>
  </target>
</project>

If I want debugging enabled (see also Ant javac parameters for more options):

  <target name="compile">
    <mkdir dir="${classes.dir}" />
    <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath" debug="true" />
  </target>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: