【问题标题】:How to execute ant and close the command prompt using Runtime.getRuntime().exec()如何使用 Runtime.getRuntime().exec() 执行 ant 并关闭命令提示符
【发布时间】:2015-04-27 14:53:46
【问题描述】:

我想从 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文件后,应该执行剩余的代码。

当我运行此代码时,会为 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完成后执行剩余代码一次?

我尝试通过多种方式实现这一目标,但仍然面临这个问题。

【问题讨论】:

  • 您必须调用cmd 窗口吗?没有cmd /c ...就不能执行脚本吗?
  • 嗨 manouti,我删除了启动选项,但仍然没有执行剩余的代码。
  • @Manouti,它不特定于使用 cmd 窗口运行。除了 cmd winodw 之外,还有其他方法可以使用 java 运行 ant 文件吗?

标签: java batch-file command-line ant processbuilder


【解决方案1】:

您可以通过调用普通的 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 了解更多信息。

【讨论】:

  • 如何将属性文件名与目标名一起传递。使用命令提示符我会做一些像ant -propertyfile myproperty.properties targetName 这样的想法。上面的代码没有加载这个属性。如何做到这一点?
  • @Jugi 只需通过添加这些选项来更新command 列表。
  • 我已添加command.add(antExecutable); command.add("-propertyfile"); command.add("myproperty.properties"); command.add("targetName");。但它不能正常工作。
  • @Jugi 你能更新一下你的尝试和你得到的错误/意外行为吗?
  • 我的错误是我传递了错误的论点。这是我想要的完美工作。非常感谢:)
最近更新 更多