ProcessBuilder won't run with arguments [dupli

2019-07-28 16:29发布

This question already has an answer here:

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?

3条回答
乱世女痞
2楼-- · 2019-07-28 16:31

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楼-- · 2019-07-28 16:42

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.

查看更多
虎瘦雄心在
4楼-- · 2019-07-28 16:45

The complete argument is being interpreted as the executable. Use

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
查看更多
登录 后发表回答