1
votes

I'm trying execute Ant target from Java for searching directories by criteria. If run searchDirectories from console, result is OK, if from Java class, directories not found.

File buildFile = new File("build.xml");

Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
p.addBuildListener(consoleLogger);
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);

try {
    p.fireBuildStarted();
    p.fireSubBuildStarted();
    p.executeTarget("searchDirectories");
} catch (IOException e) {
    p.fireBuildFinished(e);
}

EDIT: If I call Ant from directory where contains build.xml, directories will be found. Otherwise when ant is executed via this line the result is incorrect.

ant -buildfile D:\Projects\antproj searchDirectories

I can't understand what is the problem?

1
What about Runtime#exec(String)? You can execute the same command you use in your shell.beatngu13
beatngu13, It does not work anywayGingerComa

1 Answers

1
votes

You can execute Ant from Java and print the output to System.out as follows (note that -buildfile is the same as -file or -f):

ProcessBuilder builder = new ProcessBuilder("ant", "-f", "/path/to/build.xml", "searchDirectories");
Process process = builder.start();

try (BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
    out.lines().collect(Collectors.toList()).forEach(System.out::println);
}

If your searchDirectories task produces wrong results, maybe the corresponding <target> contains a bug.