gpt4 book ai didi

Java 处理 getOutputStream 到 String

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:48 25 4
gpt4 key购买 nike

这里是 Java 8。如何读取 Process#getOutputStream() 中的数据成一个字符串?我正在尝试从 Java 内部运行一个进程并 Hook /捕获它的 STDOUT。

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("consul -v");
String capturedOutput;

OutputStream os = proc.getOutputStream();
capturedOutput = howDoIConvert(os); // <---- ???

在这里寻找确切的代码(不是像 baos.toString(codepage) 这样模糊的东西。如果我需要礼貌地 close() 也很感兴趣。

最佳答案

您从 inputStream 而不是 outputStream 读取数据。

OutputStream 用于向进程传递数据。

Process 有两个基本的输入流。一个用于标准输入,可以用 getInputStream() 检索,另一个用于错误,可以用 getErrorStream()

检索

来自 getInputStream() 的 javadoc:

Returns the input stream connected to the normal output of the subprocess

来自 getErrorStream()

Returns the input stream connected to the error output of the subprocess.

关于流的注意事项:从 java 程序的角度来看,Process 是一个外部程序。当您需要向您从 java 编写到该程序的外部程序添加一些输入时(因此 java 程序的输出是 Process 的输入)。相反,如果外部程序写了一些东西,您就可以读取它(因此 Process 的输出是 java 程序的输入)。

Java                   Data direction   External Process
_____________________________________________________________

write to OutputStream ------------> read from InputStream
read from InputStream <------------ write to OutputStream

关于Java 处理 getOutputStream 到 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612717/

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