View RSS Feed

My Java Tips

ANT (Example)

Rate this Entry
by , 11-07-2011 at 05:55 PM (809 Views)
This post is all about an ANT example. I will present an ANT build script that will compile a project, and will generate a JAR file.

I will name the project as Project X and will provide some useful description.

<!--?xml version="1.0"?-->
<project default="dist" name="Project X">
<description>Test project</description>

Now is the time to define the properties. Properties are like variable we use in Java or C++.

<property name="srcDir" location="src"></property>
<property name="buildDir" location="build"></property>
<property name="distDir" location="dist"></property>

I defined 3 properties. First one contains the path of source directory, second one contains the path of build directory (where class files will be generated), and the third one contains the path of distribution directory, which will actually contain the JAR file.

Now, lets define the targets. First target is init, which simply creates 2 directories using ANT built in commands.

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

After defining the init target, I'll define a compile target as follows:

<target name="compile" depends="init">
<javac srcdir="${srcDir}" destdir="${buildDir}">

It depends on init, so if you run this one, init will be executed first. Compile target compiles the code in the source directors and generates the class files in the build directory.

Time to define the third target which will generate the JAR file in the distribution directors. It is named dist and it depends on compile.

<target name="dist" depends="compile">
<jar destfile="${distDir}/package-${DSTAMP}.jar" basedir="${buildDir}">
<attribute name="Built-By" value="${}"></attribute>
<attribute name="Main-Class" value="package.Main"></attribute>
<jar destfile="${distDir}/package-src-${DSTAMP}.jar" basedir="${srcDir}">

We are generating 2 JARs one with source code and the other without source code.

At the end, simply I will define a clean target to remove the unwanted directories.

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

Hope this helps.

Submit "ANT (Example)" to Facebook Submit "ANT (Example)" to Digg Submit "ANT (Example)" to Submit "ANT (Example)" to StumbleUpon Submit "ANT (Example)" to Google

Tags: None Add / Edit Tags
Ant , XML