Reputation: 3750
I need to pass data from one process to another through the blocking input/output streams. Is there anything ready to be used in JVM world?
How do I make the output of one process become the input of another process?
Upvotes: 1
Views: 220
Reputation:
From a single thread you can use:
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);
}
If you want to use two threads, you can use 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);
}
Upvotes: 1