问题
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