从java进程获取输出

时间:2016-03-03 06:08:23

标签: java javafx javafx-2

我正在构建一个javaFx应用程序我正在使用java进程构建器类运行命令。

ProcessBuilder builder = new ProcessBuilder(runCommand);
builder.redirectErrorStream(true);
Process process = builder.start();
try {
    process.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}

我正在尝试从过程中获得输出我尝试了两种不同的方式,但我无法得到它。

InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
String line1=null;
while ((line1 = reader.readLine()) != null) {
    System.out.println(line1);
}
BufferedReader errorred = new BufferedReader (new InputStreamReader(stderr));
while ((line1 = errorred.readLine()) != null) {
    System.out.println(line1);
}

我也尝试了这个:

ProcessBuilder builder = new ProcessBuilder(runCommand);
//String outputLogs = new VerboseProcess(new ProcessBuilder(""));
builder.redirectErrorStream(true);
builder.redirectOutput(Redirect.INHERIT);
builder.redirectError(Redirect.INHERIT);
builder.redirectInput(Redirect.INHERIT);
Process process = builder.start();
try {
    process.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:1)

我相信错误在其他地方。以下代码段基于您发布的代码

ProcessBuilder builder = new ProcessBuilder("java.exe", "-version");
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
int exitValue = process.exitValue();
System.out.println("exitValue = " + exitValue);

InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
String line1 = null;
while ((line1 = reader.readLine()) != null) {
    System.out.println(line1);
}
BufferedReader errorred = new BufferedReader(new InputStreamReader(stderr));
while ((line1 = errorred.readLine()) != null) {
    System.out.println(line1);
}

并在控制台上生成以下输出

exitValue = 0
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)

如果new ProcessBuilder(command...)中指定的命令不存在或者不在PATH中,则抛出IOException

Cannot run program "...": CreateProcess error=2, The system \
    cannot find the file specified

如果你没有得到任何输出。以下可能是原因:

  • 该过程未向stdout / stderr打印任何内容
  • 您的runcommand在后​​台流程中启动流程,例如在Linux / OSX command &或Windows start command.exe