java execute shell command and get output code example

Example 1: 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();
}

Example 2: java get command line output

private static void GetOutput(final Process process) {
    new Thread() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null; 
            try {
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

Tags:

Java Example