2

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?

ST3
  • 8,826
  • 3
  • 68
  • 92
user2513924
  • 2,070
  • 3
  • 15
  • 23

3 Answers3

11

The complete argument is being interpreted as the executable. Use

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

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");
Community
  • 1
  • 1
ST3
  • 8,826
  • 3
  • 68
  • 92
-2

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.

Robin Green
  • 32,079
  • 16
  • 104
  • 187