ProcessBuilder won't run with arguments [duplicate]

家住魔仙堡 提交于 2020-01-15 20:16:09

问题


I am trying to run "java -version" using ProcessBuilder:

processBuilder = new ProcessBuilder("java -version");
process = processBuilder.start();

However I get an error:

java.io.IOException: Cannot run program "java -version": CreateProcess error=2, The system cannot find the file specified

When I remove the "-version" and do:

processBuilder = new ProcessBuilder("java");
process = processBuilder.start();

it runs fine and I get the normal help guide output.

How can I get it to run the argument too?


回答1:


The complete argument is being interpreted as the executable. Use

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");



回答2:


Constructor Summary

ProcessBuilder(List command) - Constructs a process builder with the specified operating system program and arguments.

ProcessBuilder(String... command) - Constructs a process builder with the specified operating system program and arguments.

So you need to use:

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");



回答3:


You are probably making this unnecessarily complicated. If all you want to do is find out the version of Java you are running on, use System.getProperty("java.specification.version").

Also, your code will fail if Java is not on the PATH, but this way will still work.



来源:https://stackoverflow.com/questions/19346031/processbuilder-wont-run-with-arguments

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