Java Language Process Using the ProcessBuilder class


The ProcessBuilder class makes it easy to send a command through the command line. All it requires is a List of Strings that make up the commands to be entered. You simply call the start() method on your ProcessBuilder instance to execute the command.

If you have a program called Add.exe which takes two arguments and adds them, the code would look something like this:

List<String> cmds = new ArrayList<>();
cmds.add("Add.exe"); //the name of the application to be run
cmds.add("1"); //the first argument
cmds.add("5"); //the second argument

ProcessBuilder pb = new ProcessBuilder(cmds);

//Set the working directory of the ProcessBuilder so it can find the .exe
//Alternatively you can just pass in the absolute file path of the .exe
File myWorkingDirectory = new File(yourFilePathNameGoesHere);

try {
    Process p = pb.start(); 
} catch (IOException e) {

Some things to keep in mind:

  • The array of commands must all be a String array
  • The commands must be in the order (in the array) that they would be if you made the call to the program in the command line itself (ie. the name of the .exe can't go after the first argument
  • When setting the working directory you need to pass in a File object and not just the file name as a String