gpt4 book ai didi

java - 从 java 进程获取输出

转载 作者:行者123 更新时间:2023-11-30 07:33:15 28 4
gpt4 key购买 nike

我正在构建一个 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 打印任何内容
  • 您的runco​​mmand在后台进程中启动该进程,例如在 Linux/OSX 上 command & 或在 Windows 上 start command.exe

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com