ProcessBuilder cannot find the specified file while Process can

我与影子孤独终老i 提交于 2019-12-01 05:04:40

问题


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?


回答1:


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




回答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".



来源:https://stackoverflow.com/questions/14999489/processbuilder-cannot-find-the-specified-file-while-process-can

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!