Lets take this time in consideration a real life project. Most of the time Ant is used to compile and build java projects. This means generating, compiling and building jar files. For this we are going to define severals tasks. Lets consider the we create a buid.xml file in the directory where sources are located. The sources are put in the subdirectory called src. We also need to include a jar in the classpath while compiling. We are going to create a separate property file to define the location of this file:

#===================================
#	File Name: build.properties
#===================================

env.LIB=c://java//thirdparty//lib

The ant task contains a few tasks for doing the following operations:
1. Clean the build directory if exists.
2. Create the build directory where the new classes will be built.
3. Compile the java classes.
4. Build a jar file from the java classes.

Here is the build.xml file. Note the dependencies between the tasks and how the properties are defined in the ant xml file or loaded from the properties file:

<project name="how-to-use-ant" basedir="." default="jar">

	<property name="build" value="build"/>
	<property file="build.properties"/>
	
	<target name="clean">
		<delete dir="${build}"/>
	</target>

	<target name="init" depends="clean">
		<mkdir dir="${build}"/>
	</target>	
	
	<target name="compile" depends="init">
		<!-- Compile the java code -->
		<javac srcdir="src" destdir="${build}">
			<classpath>
				<pathelement location="${env.LIB}/required-jar1.jar"/>
				<pathelement location="${env.LIB}/required-jar2.jar"/>
			</classpath>
		</javac>
	</target>	
	
	<target name="jar" depends="compile">
		<!-- Build the jar file -->
		<jar basedir="${build}" destfile="${build}/new-jar.jar"/>
	</target>
	
</project>

Now that you’ve seen how to create an ant task you might ask why you need an ant build file for building a jar file. This can be done as well with a few batch commands which will take only a 4 lines bat file. There are certain advantages. The ant files can be easily parametrized and reused, sub projects cand be created, lots of tasks are implemented, covering most of the operations you want to do (junits, sql operations, zip file tasks, tasks for replacing and editing text and xml files, …) and new tasks can be implemented in java and used in any ant file.

Did you enjoy this tutorial? Be sure to subscribe to the my RSS feed not to miss my new posts!
... or make it popular on