gpt4 book ai didi

java - 使用 Java 中的 ProcessBuilder 将一个进程的输出重定向到另一个进程的输入

转载 作者:搜寻专家 更新时间:2023-11-01 02:40:04 24 4
gpt4 key购买 nike

我有两个由 processBuilders 定义的进程:

ProcessBuilder pb1 = new ProcessBuilder (...)
ProcessBuilder pb2 = new ProcessBuilder (...)

我希望 pb1 的输出成为 pb2 的输入。我在文档中发现我可以使用管道从另一个进程读取 pb2 的输入:

pb2.redirectInput(Redirect.PIPE);

但是,如何指定我希望此管道从 pb1 的输出中读取?

最佳答案

static ProcessBuilder.Redirect INHERIT Indicates that subprocess I/Osource or destination will be the same as those of the currentprocess.

static ProcessBuilder.Redirect PIPE Indicates that subprocess I/Owill be connected to the current Java process over a pipe.

所以我认为其中之一不会帮助您将一个进程的输出重定向到另一个进程的输入。您必须自己实现。

实现:

public class RedirectStreams {
public RedirectStreams(Process process1, Process process2) {
final Process tmpProcess1 = process1;
final Process tmpProcess2 = process2;
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(tmpProcess1.getInputStream()));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(tmpProcess2.getOutputStream()));
String lineToPipe;

try {

while ((lineToPipe = bufferedReader.readLine()) != null){
System.out.println("Output process1 / Input process2:" + lineToPipe);
bufferedWriter.write(lineToPipe + '\n');
bufferedWriter.flush();
}

} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

}

这个肯定可以设计得更好我还没有测试过它是否可以安全运行,但它可以完成工作。

用法:

RedirectStreams redirectStreams = new RedirectStreams(process1,process2);

测试:

public class ProcessPipeTest {
@Test public void testPipe(){
try {

Process process1 = new ProcessBuilder("/bin/bash").start();
Process process2 = new ProcessBuilder("/bin/bash").start();

RedirectStreams redirectStreams = new RedirectStreams(process1,process2);


BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(process1.getOutputStream()));
String command = "echo echo echo";
System.out.println("Input process1: " + command);
bufferedWriter.write(command + '\n');
bufferedWriter.close();


BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process2.getInputStream()));
String actualOutput = bufferedReader.readLine();
System.out.println("Output process2: " + actualOutput);
assertEquals("echo",actualOutput);

} catch (IOException e) {
e.printStackTrace();
}
}
}

输出:

Input process1: echo echo echo

Output process1 / Input process2:echo echo

Output process2: echo

关于java - 使用 Java 中的 ProcessBuilder 将一个进程的输出重定向到另一个进程的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706921/

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