Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProcessBuilder cannot find the specified file while Process can

I am trying to run a jar file from a Java program and I succeed using getRuntime():

Process processAlgo = Runtime.getRuntime().exec("java -jar "+algoPath);

However when I try using ProcessBuilder I get the The system cannot find the file specified exception:

ProcessBuilder builder = new ProcessBuilder("java -jar " + algoPath);
Process processAlgo = builder.start();

I tried to change the location of the specified file and also indicated its full path but it won't work. What could cause the problem?

like image 756
Limbo Exile Avatar asked Dec 27 '22 08:12

Limbo Exile


1 Answers

ProcessBuilder expects it's parameters to passed in separately.

That is, for each command and argument, ProcessBuilder expects to see it as a separate parameter.

Currently you're telling it to run "java -jar what ever the value of algoPath is"...which from ProcessBuilder's perspective, is an invalid command.

Try...

ProcessBuilder builder = new ProcessBuilder("java",  "-jar", algoPath);
Process processAlgo = builder.start();

Instead.

If algoPath contains spaces (ie more then one argument), they will need to be separated into individual parameters as well, otherwise your program will not execute, as Java will see the algoPath as a single parameter.

Check the JavaDocs for more details

like image 53
MadProgrammer Avatar answered Dec 28 '22 23:12

MadProgrammer