I am trying to use Java to find out the versions of Java installed on a machine. I have:
List<String> commands = new ArrayList<String>();
commands.add("java.exe");
commands.add("-version");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("C:\\Program Files\\Java\\jdk1.6.0_45\\bin"));
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
However, when this is run, the while loop is never executed as the stdInput is empty. If I take out the commands.add("-version")
, it will get the input that is output when running "java.exe" command on command line, so it seems adding the -version
arguement is causing issues and this also indicates that the directory and java.exe commands are correct. Any help would be appreciated.
The output of java -version
is sent to the error stream - reading from that stream should result in the proper output:
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getErrorStream()));
Alternatively, you can call redirectErrorStream(true)
to merge the Input and Error streams. If you just wish to just print to the command line, you can use inheritIO
on the ProcessBuilder.
The currently running java version can be found without the need for a ProcessBuilder
by retrieving the appropriate System property
System.out.println(System.getProperty("java.version"));