简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM