简体   繁体   English

在Java中运行命令行程序而没有绝对路径

[英]Run command-line program in Java without absolute path

I'm trying to run Ant from a Java program. 我正在尝试从Java程序运行Ant。 This works: 这有效:

// Compile project
ProcessBuilder pb =
        new ProcessBuilder("/usr/local/Cellar/ant/1.9.6/libexec/bin/ant", "-f", pathToProject + "build.xml");
Process p = pb.start();
p.waitFor();

However, this program will be used on machines other than my own, so I'd rather instantiate the ProcessBuilder like this: 但是,该程序将在我自己的机器以外的其他机器上使用,所以我宁愿像这样实例化ProcessBuilder:

new ProcessBuilder("ant", "-f", pathToProject + "build.xml");

Although ant -f build.xml works on my Mac terminal, placing the above code in my program outputs java.io.IOException: Cannot run program "ant": error=2, No such file or directory . 尽管ant -f build.xml在我的Mac终端上ant -f build.xml ,但是将以上代码放置在程序输出中java.io.IOException: Cannot run program "ant": error=2, No such file or directory

How can I programmatically show ProcessBuilder where Ant is located? 如何以编程方式显示ProcessBuilder Ant所在的位置? This program will be run on OS X and possibly Ubuntu. 该程序将在OS X以及可能的Ubuntu上运行。

Note: This question is not Ant-specific. 注意:此问题不是特定于Ant的。 I need use ProcessBuilder to invoke other command-line tools as well. 我还需要使用ProcessBuilder来调用其他命令行工具。

通过使Ant可通过属性文件进行自定义,将其绝对路径注入ProcessBuilder。这样,您只需在属性文件中提供相应的路径即可在多个环境中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM