Executing Ant Tasks Programatically

Login | Register

Executing Ant Tasks Programatically

Executing ant tasks programatically via Java is fairly straightforward as shown in the following code sample.

To compile and run the following code, ensure you have ant.jar, xercesImpl.jar, xml-apis.jar and ant-launcher.jar (all from the ant lib directory) on your claspath.

/* 
 * AntRunner.java 
 */
 
import java.io.File; 
import org.apache.tools.ant.DefaultLogger; 
import org.apache.tools.ant.Project; 
import org.apache.tools.ant.ProjectHelper; 
import org.apache.tools.ant.taskdefs.Ant; 
 
public class AntRunner { 
 
    public AntRunner() { 
    } 
 
    public static void main(String args[]) throws Exception { 
        File buildFile = new File("/path/to/build.xml"); 
        Project p = new Project(); 
        p.setUserProperty("ant.file", buildFile.getAbsolutePath()); 
        p.init(); 
        ProjectHelper helper = ProjectHelper.getProjectHelper(); 
        p.addReference("ant.projectHelper", helper); 
        helper.parse(p, buildFile); 
        DefaultLogger consoleLogger = new DefaultLogger(); 
        consoleLogger.setErrorPrintStream(System.err); 
        consoleLogger.setOutputPrintStream(System.out); 
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO); 
        p.addBuildListener(consoleLogger); 
        p.executeTarget(p.getDefaultTarget()); 
    } 
}

About

At Develop In Java, we've been a part of the Java community for over 10 years. If there's anything you'd like us to cover, just ask !

Current versions

  • Java - 1.8
  • Java EE - 7
  • Spring - 4.x