|
Using Ant to Build Code
Project-based Ant provides an array of useful tasks you can use inside any application
by Kevin Jones
Posted May 12, 2004
Ant, as we all know, is a great tool for building and helping to manage projects. To use Ant a developer creates an Ant build file and passes the build file to the Ant run time. A build file would look something like this:
<project name="foo"
default="build">
<target name="CopyFiles"
depends="prepare"
description="Copy files">
<copy toDir="foo">
<fileset dir="bar"
includes=
"**/*.propeties"/>
</copy>
</target>
</project>
In Ant each of these elements is parsed, and an appropriate Java object is created. Each object is then used to perform the appropriate work. For example, each project has a <project…> element, and for each project an org.apache.tools.ant.Project object is created. For each task there will be a specific type of org.apache.tools.ant.Task object created. For the copy task the object is an org.apache.tools.ant.taskdefs.Copy object. The fileset is associated with an org.apache.tools.ant.types.FileSet object, and this, along with the attributes, is associated with the copy task. The task is then executed.
Ant comes with any number of tasks. You want to compile code, run the javac task, and create directories: use mkdir, zip, unzip, tar, sql, cvs, checksum, copy, delete, ftp, get, junit, and so on. And what are these tasks? Simply, they are Java components that can be used in your code, which means that if you need to copy a group of files from one location to another, for example, rather than write the iteration and copy code yourself you can use the Ant copy task. Similarly, if you need to download data from an HTTP or FTP server, or if you need to zip or unzip files, Ant provides a toolbox of useful tasks that can be used inside any application.
Let's look at an example to see how this works. In this example we will show how to use the Ant copy task to copy files from one directory to another, and we'll also see how to use the fileset nested datatype.
Ant is project based and the Ant project is modeled by the Project class. All tasks in Ant require a reference to the Project, so the first thing to do when using Ant tasks is to create and initialize an instance of Project:
static Project createProject()
{
Project project =
new Project();
project.init();
project.getBaseDir();
return project;
}
This task will create a new project instance, initialize it, and set the base directory to the current directory if the base directory has not already been set (the getBaseDir() method checks first).
Once you have the project you can then use the project to create the task:
Project project =
createProject();
Copy copy = (Copy)
project.createTask("copy");
copy.init();
Back to top
|