I found, we can find out Java version using System.getProperty("java.version").
from here - Getting Java version at runtime
But I have already done so coding using Runtime.getRuntime().exec(commands) -
String[] commands ={"java", "-version"};
String line;
String cmdOutput = "";
try {
Process process = Runtime.getRuntime().exec(commands);
process.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
cmdOutput += (line + "\n");
}
System.out.println("output "+cmdOutput);
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
But getting blank output.
When I run java -version from command prompt, we get version, I feel it should also return same output.
Before I discard it and use System.getProperty("java.version"), Can I please know what I am missing here ?
Thanks in advance.
2 Answers 2
You don't get the version in your code because: java -version prints to the error stream, rather than stdout, I don't know why.
You can show this with:
java -version > output.txt
and see that it's still printed to your console, and nothing is in output.txt.
Or with:
java -version 2> error.txt
and see that nothing is printed and the version information is in error.txt
The question as to why it happens was asked here: Why does 'java -version' go to stderr?
2 Comments
2 in java -version 2 ?public static String getJavaVersion()
{
String method = "getJavaVersion";
String javaVersion = "";
try
{
// Command: wmic datafile where name="C:\\Windows\\System32\\msiexec.exe" get Version /value
Process process = Runtime.getRuntime().exec("java -version");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
javaVersion = reader.readLine();
System.out.println("Method: "+method+" - "+javaVersion);
while(javaVersion!= null)
{
if(javaVersion.trim().startsWith("Version"))
{
System.out.println("Method: "+method+" - "+javaVersion);
return javaVersion;
}
javaVersion=reader.readLine();
}// end while
}
catch (IOException e)
{
System.out.println("Method: "+method+" Could not check version "+e);
e.printStackTrace();
return "";
}
return javaVersion;
}
Runtime.execto get the java version, unless you intend to never give the application to anyone else or to ever run it on a different machine. First, the JRE may or may not in thePATHsystem variable. Second, even if it is, there is no guarantee that your application will be run with the same JRE as the one present in thePATH