【发布时间】:2021-03-28 10:54:45
【问题描述】:
我需要通过阻塞的输入/输出流将数据从一个进程传递到另一个进程。有什么东西可以在 JVM 世界中使用吗?
如何让一个进程的输出成为另一个进程的输入?
【问题讨论】:
我需要通过阻塞的输入/输出流将数据从一个进程传递到另一个进程。有什么东西可以在 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和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);
}
【讨论】: