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

czq61nw1  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(370)

我需要通过阻塞的输入/输出流将数据从一个进程传递到另一个进程。有什么东西可以在jvm世界中使用吗?
如何使一个进程的输出变成另一个进程的输入?

gj3fmq9x

gj3fmq9x1#

从单个线程可以使用:

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 以及 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);
}

相关问题