我正在构建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();
}

最佳答案

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

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

关于java - 从Java进程获取输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35764459/

10-09 06:44
查看更多