如何使用 Runtime.getRuntime().exec() 执行 ant 并关闭命令提示符

How to execute ant and close the command prompt using Runtime.getRuntime().exec()

我想从 java 执行一个 ant 文件。所以我决定使用 Runtime.getRuntime().exec() 来实现这一点。我的 java 文件如下所示,

Process p = Runtime.getRuntime().exec("cmd /c start ant mytarget -Darg1="+arg1+" -Darg2="+arg2+" ", null, new File("E:/ant_demo"));

System.out.println("Ant file executed");
...
...
..
System.out.println("Completed");

我的目标是 运行 路径 E:/ant_demo 中可用的 ant 文件,参数很少。完成ant文件后,应该执行剩余的代码。

当我 运行 这段代码时,一个单独的命令提示符 window 会为 ant 打开,并且在 ant 文件完成之前,其余代码也会并行执行。为了让代码等到蚂蚁完成,我改变了我的代码如下,

    Process p = Runtime.getRuntime().exec("cmd /c start /wait ant mytarget -Darg1="+arg1+" -Darg2="+arg2+" ", null, new File("E:/ant_demo"));
    p.waitFor();

    System.out.println("Ant file executed");
    ...
    ...
    ..
    System.out.println("Completed");

此更改后,即使在 ant 完成后,剩余的代码也不会执行,用于 ant 的命令提示符仍保持打开状态。当我手动关闭用于 ant 的命令提示符时,将执行剩余的代码。

如何让ant使用的命令提示符自动关闭?或者如何将我的代码更改为运行 ant文件并在ant完成后执行一次剩余代码?

我尝试了很多方法来实现这个,但仍然面临这个问题。

您可以通过调用普通的 Ant 可执行文件来 运行 Ant 脚本(ProcessBuilder 可以)。 ANT_HOME 环境变量通常指向 Ant 安装,因此您可以从中构建可执行文件的路径:

String antHome = System.getenv().get("ANT_HOME");
String antExecutable = antHome + File.separator + "bin" + File.separator + "ant.bat";

List<String> command = new ArrayList<String>();
command.add(antExecutable);
command.add("mytarget");
command.add("-Darg1="+arg1);
command.add("-Darg2="+arg2);
command.add("-propertyfile");
command.add("myproperty.properties");

ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(new File("E:/ant_demo")); // set working directory
Process process = processBuilder.start(); // run process

// get an input stream connected to the normal output of the process
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while (( line = reader.readLine ()) != null) {
    System.out.println(line);
}
System.out.println("Ant file executed");
...
...
System.out.println("Completed");

请注意,在调用 ProcessBuilder#start() 之后,将检索输入流以读取 Ant 命令的输出并将其打印到 System.out。有关详细信息,请参阅 Java Process with Input/Output Stream