在 Java 中使用 Runtime.exec() [英] using Runtime.exec() in Java
问题描述
在 Java 中你必须做什么才能让 Runtime.exec() 运行路径上的程序?我正在尝试运行已放入路径 (/usr/local/bin) 中的 gpsbabel.
What do you have to do in Java to get the Runtime.exec() to run a program that is on the path? I'm trying to run gpsbabel which I have put into the path (/usr/local/bin).
public class GpxLib {
public static void main(String[] args) {
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("gpsbabel -i garmin -f usb: -o gpx -F -");
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true)
{
String s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.readLine();
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
推荐答案
它将继承 Java 进程的路径.因此,无论 Java 进程具有什么环境,生成的进程也将具有.以下是检查环境的方法:
It will inherit the path from the Java process. So whatever environment the Java process has, the spawned process will have as well. Here's how to check the environment:
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
您是否设置了 PATH
并 将其导出?如果您不导出它,则它不可用于子进程.
Have you set the PATH
and exported it ? If you don't export it, then it's not available to subprocesses.
此外,您必须同时使用 stdout 和 stderr,以防止阻塞.否则在某些情况下东西会起作用,那么您生成的进程将输出不同数量的数据,一切都会停止.
Additionally, you must consume stdout and stderr concurrently, to prevent blocking. Otherwise stuff will work in some circumstances, then your spawned process will output a different quantity of data and everything will grind to a halt.
有关详细信息,请参阅此答案.
See this answer for more details.
这篇关于在 Java 中使用 Runtime.exec()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!