how to print stdout parallely in java which exe cuting code example

Example: java runtime exec get output

private static void execCommand() {
  String[] command = {"echo", "Hello", "world."};
  
  new Thread(() -> {
    try {
      ProcessBuilder builder = new ProcessBuilder(command);
      builder.redirectErrorStream(true);
      final Process proc = builder.start();
      BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String s = null;
      while ((s = in.readLine()) != null) {
        System.out.println(s);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }).start();
}

Tags:

Java Example