Java 运行时未在 Mac 上捕获 STDOUT
Java Runtime not capturing STDOUT on Mac
Mac OS 此处,但 正在寻找与平台无关的解决方案。 另外请注意,尽管此处提到了 Consul,但它是只是任意的,解决方案应该与 Consul 无关,也不需要知道 Consul。
当我打开 shell 和 运行 consul -v
(以确定本地是否安装了 Consul)时,我得到以下 STDOUT:
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 [is] not found。
我的代码有什么问题?为什么它不“挂钩”/捕获 STDOUT?
使用Process#getInputStream() to read STDOUT or 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.");
}
}
}
Mac OS 此处,但 正在寻找与平台无关的解决方案。 另外请注意,尽管此处提到了 Consul,但它是只是任意的,解决方案应该与 Consul 无关,也不需要知道 Consul。
当我打开 shell 和 运行 consul -v
(以确定本地是否安装了 Consul)时,我得到以下 STDOUT:
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 [is] not found。
我的代码有什么问题?为什么它不“挂钩”/捕获 STDOUT?
使用Process#getInputStream() to read STDOUT or 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.");
}
}
}