Invoke ant from java, then return to java after ant termination

☆樱花仙子☆ 提交于 2019-12-19 09:27:05

问题


so far i have invoked ant script from java. Now the question is, is it possible to resume java execution after the termination of the ant build?

How do i do it?


回答1:


org.apache.tools.ant.Main's main() and startAnt() methods call the exit() method which in turn calls System.exit(code).

The solution (assuming you call one of those methods) is to sub-class org.apache.tools.ant.Main and override the exit() method

/**
 * This operation is expected to call {@link System#exit(int)}, which
 * is what the base version does.
 * However, it is possible to do something else.
 * @param exitCode code to exit with
 */
protected void exit(int exitCode) {
    System.exit(exitCode);
}



回答2:


Check out the source of Ant's main class, org.apache.tools.ant.Main. You can try to invoke its main or start method directly, or copy some of its logic to your application. After those methods finish, your application should continue execution.

EDIT:

The answer by Paul Cager is correct, I somehow missed the fact that Ant's Main calls System.exit().

Another thing about the main/start/startAnt methods is that they expect the arguments as an array of strings. This can be handy, but it's not particularly typesafe or object-oriented. To invoke Ant for a given buildfile and target, you can use something like this:

public static void runAnt(String buildfile, String target) throws Exception {
    File buildFile = new File(buildfile);
    Exception error = null;
    org.apache.tools.ant.Project project = new org.apache.tools.ant.Project();
    try {
        project.addBuildListener(new org.apache.tools.ant.listener.Log4jListener());
        project.fireBuildStarted();
        project.init();
        project.setUserProperty(org.apache.tools.ant.MagicNames.ANT_FILE, buildFile.getAbsolutePath());
        org.apache.tools.ant.ProjectHelper.configureProject(project, buildFile);
        project.executeTarget(target);
    } catch (Exception e) {
        error = e;
        throw e;
    } finally {
        project.fireBuildFinished(error);
    }
}



回答3:


Process p = Runtme.getRuntime.exec("ant mytarget");
p.waitFor();  // waits until process completes before continuing to next line
// continue Java program here


来源:https://stackoverflow.com/questions/8714262/invoke-ant-from-java-then-return-to-java-after-ant-termination

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!