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:
        ProcessBuilder pb = new ProcessBuilder();
  1. Set the command to tree and the output and error to the same as that of the current Java process:
        pb.command("tree").inheritIO();
  1. Set the directory to whatever directory you want. I set it as the root folder:
        pb.directory(new File("/root"));
  1. Start the process and wait for it to exit:
        Process p = pb.start();
        int exitValue = p.waitFor();
  1. Compile and run using the following commands:
      $ javac -d mods --module-source-path src $(find src -name *.java)
      $ java -p mods -m process/com.packt.process.ChangeWorkDirectoryDemo
  1. The output will be the recursive contents of the directory, specified in the directory() method of the ProcessBuilder object, ...

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