Limbo Exile
Limbo Exile

Reputation: 1351

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?

Upvotes: 4

Views: 5503

Answers (2)

Yes the "java" should be your first parameter, and every other argument has to sent in other parameter.

I had a problem with executing this line "bash /path/script.sh arg1 arg2"... because the first parameter I was passing was "bash /path/script.sh", "arg1", "arg3"... getting the Exception: Command not found by JAVA.

When I separate in parameters each element, then worked fine. "bash", "/path/script", "arg1", "arg2".

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347204

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

Upvotes: 10

Related Questions