Reputation: 320
I have some example code where a process builder is used and given two commands to execute, but I can't fully understand what each line of code is doing.
Also the commands don't seem to be actually executing.
Code:
public static void main(String[] args) {
ArrayList<String> commands = new ArrayList(); // commands in a processbuilder is an Arraylist of of strings
commands.add("myfile.pdf"); // supposed to open the file?
commands.add("bash\", \"-c\", \"ls"); // supposed to use ls command in terminal
execute(commands); // should execute the two commands above
System.out.println("executed commands"); // only thing that actually happens
}
public static void execute(ArrayList<String> command) {
try {
ProcessBuilder builder = new ProcessBuilder(command); // a new builder which takes a command passed into the method
Map<String, String> environ = builder.environment(); // ???
Process p = builder.start(); // p is never used?
} catch (Exception e) {
e.printStackTrace();
}
}
I get no errors or warnings.
Tried reading the API on the processbuilder but I didn't really understand it
Upvotes: 0
Views: 752
Reputation: 1225
ProcessBuilder
helps to start external processes.
First, the command line parts (executable, parameters) are taken as a list of String
, which is very comfortable. ("command
" is rather misleading here, since it consists of executable and parameters).
Second, you can edit the environment of the new process (environment variables like "$HOME
", "$PATH
", etc.).
Your p
can be used, for example to check, if the process has finished yet or to retrieve the input/output of the new process. Since you only start the process (fire-and-forget), you don't need it here.
You may also use Runtime.exec(...)
to start an external process, which is the historical way to do so, but I think it's more comfortable to use ProcessBuilder
.
Upvotes: 2