Java I/O How to - Use multiple, concurrent runtime.exec() InputStreams








Question

We would like to know how to use multiple, concurrent runtime.exec() InputStreams.

Answer

import java.io.BufferedReader;
import java.io.InputStreamReader;
/*w ww.  j  a va  2  s  .  com*/
public class Main {
  private final static String[] comLines = { 
      "ls /var/spool/postfix",
      "ls .", 
      "javac Main.java",
      "java -version" };
  public void execute() {
    for (int i = 0; i < comLines.length; i++) {
      ExecutableChild ec = new ExecutableChild(i, comLines[i]);
      new Thread(ec).start();
    }
  }
  public static void main(String[] args) {
    new Main().execute();
  }
}
class ExecutableChild implements Runnable {
  int prIndex;
  String executable;
  public ExecutableChild(int k, String cmd) {
    prIndex = k;
    executable = cmd;
  }
  public void run() {
    try {
      Process child = Runtime.getRuntime().exec(executable);
      BufferedReader br = new BufferedReader(new InputStreamReader(
          child.getInputStream()));
      for (String s = br.readLine(); s != null; s = br.readLine()) {
        System.out.println("[" + prIndex + "] " + s);
        try {
          Thread.sleep(20);
        } catch (Exception intex) {
        }
      }
      br.close();
    } catch (Exception ioex) {
      System.err.println("IOException for process #" + prIndex + ": "
          + ioex.getMessage());
    }
  }
}