我需要通过阻塞的输入/输出流将数据从一个进程传递到另一个进程。在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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句