在Java中使用Runtime.exec() [英] using Runtime.exec() in Java

查看:109
本文介绍了在Java中使用Runtime.exec()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中你需要做什么才能让Runtime.exec()运行路径上的程序?我正在尝试运行我已放入路径的gpsbabel(/ usr / local / bin)。

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.

参见这个答案了解更多详情。

这篇关于在Java中使用Runtime.exec()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆