Apache Ant is an XML-based build tool to automate different tasks like compile, assemble, test source code, building deployment packages and run Java applications. This Hello World example shows how to invoke and run a simple Ant script programmatically using java code.

Technologies used in this article

  1. Apache Ant
  2. JDK 1.6

1. Create a Java Project and a Class with 'main' method

Create a java project ('AntExecutor') and a class ('AntExecutor') in eclipse to run a simple Ant script from java code.

Sample project structure is shown below
Sample project structure

2. Setup Java Build Path

Create a folder, named as "lib" directly under project directory "AntExecutor". Copy "ant.jar" and "xercesImpl.jar" files into that "lib" folder. Setup the build path as shown in the screenshot below
setup build path

3. Write Ant Script

Create an xml file, named as "build.xml" directly under project directory "AntExecutor" and copy the following content

File: build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="Hello World Ant Project" default="hello">
    <target name="hello">
        <echo>Hello World!</echo>
    </target>
     
    <target name="myTarget">
        <echo>My target executed</echo>
    </target>
</project>

Note: If we execute the above Ant script without specifying target name then target mentioned in the 'default' attribute will be executed.

4. Write Code

Copy the following code to the class AntExecutor

File: AntExecutor.java

package com.srccodes.example;
 
import java.io.File;
 
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
 
/**
 * @author srccodes.com
 * @version 1.0
 */
public class AntExecutor {
    /**
     * To execute the default target specified in the Ant build.xml file
     * 
     * @param buildXmlFileFullPath
     */
    public static boolean executeAntTask(String buildXmlFileFullPath) {
        return executeAntTask(buildXmlFileFullPath, null);
    }
     
    /**
     * To execute a target specified in the Ant build.xml file
     * 
     * @param buildXmlFileFullPath
     * @param target
     */
    public static boolean executeAntTask(String buildXmlFileFullPath, String target) {
        boolean success = false;
        DefaultLogger consoleLogger = getConsoleLogger();
 
        // Prepare Ant project
        Project project = new Project();
        File buildFile = new File(buildXmlFileFullPath);
        project.setUserProperty("ant.file", buildFile.getAbsolutePath());
        project.addBuildListener(consoleLogger);
 
        // Capture event for Ant script build start / stop / failure
        try {
            project.fireBuildStarted();
            project.init();
            ProjectHelper projectHelper = ProjectHelper.getProjectHelper();
            project.addReference("ant.projectHelper", projectHelper);
            projectHelper.parse(project, buildFile);
             
            // If no target specified then default target will be executed.
            String targetToExecute = (target != null && target.trim().length() > 0) ? target.trim() : project.getDefaultTarget();
            project.executeTarget(targetToExecute);
            project.fireBuildFinished(null);
            success = true;
        } catch (BuildException buildException) {
            project.fireBuildFinished(buildException);
            throw new RuntimeException("!!! Unable to restart the IEHS App !!!", buildException);
        }
         
        return success;
    }
     
    /**
     * Logger to log output generated while executing ant script in console
     * 
     * @return
     */
    private static DefaultLogger getConsoleLogger() {
        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream(System.err);
        consoleLogger.setOutputPrintStream(System.out);
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
         
        return consoleLogger;
    }
     
    /**
     * Main method to test code
     * 
     * @param args
     */
    public static void main(String[] args) {
        // Running default target of ant script
        executeAntTask("build.xml");
 
        System.out.println("-----------------------------");
         
        // Running specified target of ant script
        executeAntTask("build.xml", "myTarget");
    }
 
}

Note:
In the above code we have created a 'Project' which represents an ANT project and set the path of the ant build script.

'DefaultLogger' is used to log output of Ant execution to console. It is set to 'Project' as a listener to receive notification of events generated during ANT build.

Finally fired BuildStarted and BuildFinished to indicate ANT build is started and finished consecutively.


5. Final project structure

After doing all the changes, the overall project structure will look like this
overall project structure

6. Run Your Code

Right click on 'AntExecutor.java' and select from context menu 'Run As' --> 'Java Application'.

7. Console Output

'executeAntTask("build.xml")' code statement will execute the default target ('hello') and print 'Hello World!' in the console.

'executeAntTask("build.xml", "myTarget")' code statement will execute the target 'myTarget' and print 'My target executed' in the console.

For both cases, build failure / success message will will be printed along with the execution time.

Console

hello:
     [echo] Hello World!
 
BUILD SUCCESSFUL
Total time: 0 seconds
-----------------------------
 
myTarget:
     [echo] My target executed
 
BUILD SUCCESSFUL
Total time: 0 seconds

Download SrcCodes

All code samples shown in this post are available in the following link AntExecutor.zip