将一个进程的输出链接到另一个进程的输入

Chain the output of one process to the input of another process

我需要通过阻塞 input/output 流将数据从一个进程传递到另一个进程。有什么东西可以用在 JVM 世界吗?

如何使一个进程的输出成为另一个进程的输入?

您可以在单个线程中使用:

InputStream input = process.getInputStream();
OutputStream output = process.getOutputStream();

byte[] buffer = new byte[8192];
int amountRead;
while ((amountRead = input.read(buffer)) != -1) {
    output.write(buffer, 0, amountRead);
}

如果要使用两个线程,可以使用PipedInputStream and PipedOutputStream:

PipedOutputStream producer = new PipedOutputStream();
PipedInputStream consumer = new PipedInputStream(producer);

// This thread reads the input from one process, and publishes it to another thread
byte[] buffer = new byte[8192];
int amountRead;
while ((amountRead = input.read(buffer)) != -1) {
    producer.write(buffer, 0, amountRead);
}

// This thread consumes what has been published, and writes it to another process
byte[] buffer = new byte[8192];
int amountRead;
while ((amountRead = consumer.read(buffer)) != -1) {
    output.write(buffer, 0, amountRead);
}