O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Create a new ProcessBuilder object by specifying the command to be executed:
        ProcessBuilder pb = new ProcessBuilder("iostat");
  1. Redirect the output and error streams to the file's output and error, respectively:
        pb.redirectError(new File("error"))
          .redirectOutput(new File("output"));
  1. Start the process, and wait for it to complete:
        Process p = pb.start();
        int exitValue = p.waitFor();
  1. Read the content of the output file:
        Files.lines(Paths.get("output"))                         .forEach(l -> System.out.println(l));
  1. Read the content of the error file. This is created only if there is some error in the command:
        Files.lines(Paths.get("error"))                         .forEach(l -> System.out.println(l));
Step 4 and 5 are for our reference. This has nothing to do ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required