Using the ProcessBuilder class
suggest changeThe 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);
pb.workingDirectory(myWorkingDirectory);
try {
Process p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
Some things to keep in mind:
- The command and its arguments are a list of strings (a string array is also accepted)
- The commands must be in the same order as on the command line (i.e. 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents