Creating a Process

To create a process, first specify the attributes of the process, such as the command's name and its arguments, with the ProcessBuilder class. Then, start the process with the ProcessBuilder.start method, which returns a Process instance.

The following lines create and start a process:

  ProcessBuilder pb = new ProcessBuilder("echo", "Hello World!");
  Process p = pb.start();

In the following excerpt, the setEnvTest method sets two environment variables, horse and doc, then prints the value of these environment variables (as well as the system environment variable HOME) with the echo command:

  public static void setEnvTest() throws IOException, InterruptedException {
    ProcessBuilder pb =
      new ProcessBuilder("/bin/sh", "-c", "echo $horse $dog $HOME").inheritIO();
    pb.environment().put("horse", "oats");
    pb.environment().put("dog", "treats");
    pb.start().waitFor();
  }

This method prints the following (assuming that your home directory is /home/admin):

oats treats /home/admin