3

我想获得一个进程的输出(Git.exe确切地说)并将其转换为 String 对象。以前有时我的代码被阻止了。然后我发现这是因为该进程ErrorStream有一些输出,我必须手动捕获它(我对此不感兴趣)。我将代码更改为:

public static String runProcess(String executable, String parameter) {
    try {
        String path = String.format("%s %s", executable, parameter);
        Process pr = Runtime.getRuntime().exec(path);

        // ignore errors
        StringWriter errors = new StringWriter();
        IOUtils.copy(pr.getErrorStream(), errors);

        StringWriter writer = new StringWriter();
        IOUtils.copy(pr.getInputStream(), writer);

        pr.waitFor();
        return writer.toString();
    } catch (Exception e) {
        return null;
    }
}

现在它工作得很好,但话又说回来,有时它会在这一行再次被阻止: IOUtils.copy(pr.getErrorStream(), errors);.

有什么方法可以让我在git.exe不碰到块的情况下获得输出?谢谢。

4

2 回答 2

3

使用这篇漂亮的文章StreamGobbler那里描述的课程(我对其进行了一些修改),我解决了这个问题。我的实现StreamGobbler

class StreamGobbler extends Thread {
    InputStream is;
    String output;

    StreamGobbler(InputStream is) {
        this.is = is;
    }

    public String getOutput() {
        return output;
    }

    public void run() {
        try {
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer);
            output = writer.toString();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

我的功能是:

public static String runProcess(String executable, String parameter) {
    try {
        String path = String.format("%s %s", executable, parameter);
        Process pr = Runtime.getRuntime().exec(path);

        StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream());
        StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream());

        // kick them off concurrently
        errorGobbler.start();
        outputGobbler.start();

        pr.waitFor();
        return outputGobbler.getOutput();
    } catch (Exception e) {
        return null;
    }
}
于 2013-01-21T16:03:54.397 回答
1

使用 ProcessBuilder 或 Apache commons-exec。

您发布的代码有错误,这是一个很难解决的话题。

于 2013-01-21T16:16:56.787 回答