我想從我的java類運行一個ant腳本runANTScript.xml。該腳本位於我的Web應用程序的SCRIPTS /文件夾中。我試圖運行文件中像這樣從java類執行ant腳本
StringBuffer output = new StringBuffer();
String command="ant -f SCRIPTS/runANTScript.xml"
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
但是,這給出了一個錯誤
java.io.IOException: Cannot run program "ant": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
at java.lang.Runtime.exec(Runtime.java:617)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at my.Abc.executeCommand(Abc.java:48)
我可以使用下面的代碼,但它導入類從的ant.jar跑,我不希望使用jar文件。
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
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;
}
將ant庫添加到您的classapth並將調用Runtmie.exec(...)與 – Verhagen