Java Runtime无法在Mac上捕获STDOUT

时间:2015-09-15 15:11:06

标签: java macos shell stdout

Mac OS在这里,但是寻找与平台无关的解决方案。另请注意,即使这里提到了Consul,它也是随意的,解决方案应该与之无关,也不是需要知识,领事。

当我打开一个shell并运行consul -v(以确定本地是否安装了Consul)时,我得到以下标准:

Consul v0.5.2
Consul Protocol: 2 (Understands back to: 1)

当我运行以下代码时:

public class VerifyConsul {
    public static void main(String[] args) {
        PrintStream oldPS = System.out;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc;

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream newPS = new PrintStream(baos);

            System.setOut(newPS);
            proc = runtime.exec(“consul -v”);
            proc.waitFor();

            String capturedOut = baos.toString();

            if(capturedOut.isEmpty()) {
                throw new IllegalArgumentException(“Consul not found.”);
            }
        } catch(Throwable t) {
            System.out.println(t.getMessage());
            System.setOut(oldPS);
        }
    }
}

我得到IllegalArgumentException声明 Consul [未找到]

我的代码出了什么问题?为什么不“挂钩”/捕捉STDOUT?

1 个答案:

答案 0 :(得分:1)

使用Process#getInputStream()读取STDOUT或Process#getErrorStream()读取STDERR

以下是一个示例(使用java进程并读取STDERR):

package so32589604;

import org.apache.commons.io.IOUtils;

public class App {
    public static void main(String[] args) throws Exception {
        final Runtime runtime = Runtime.getRuntime();
        final Process proc = runtime.exec("java -version");
        proc.waitFor();
        // IOUtils from apache commons-io
        final String capturedOut = IOUtils.toString(proc.getErrorStream());

        System.out.println("output = " + capturedOut);
        if(capturedOut.isEmpty()) {
            throw new IllegalArgumentException("Java not found.");
        }
    }
}