0

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.

2
  • Does this question help? Commented Jun 3, 2015 at 18:53
  • Nope, refer to @Copeg question Commented Jun 3, 2015 at 18:54

2 Answers 2

7

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

I am writing something that gets all versions of Java installed on machines, so I cannot use this method. I need to recursively look in well known locations and run "java.exe -version"
Ahh there it is, thank you... why would that be sent to error stream??
1

java -version prints to stderr. Try using:

ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);

That will put stderr in the same stream as stdout and the rest of your code can look as it does now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.