Checking/getting JAVA_HOME Variable from Java

2019-07-06 01:26发布

问题:

Inside a Java program, how can I read the JAVA_HOME variable (to be sure it is set the correct way)? Similarly, how can I get the path of the bin folder? That is, the path usually set in Windows via:

path %path%;%JAVA_HOME%\bin

Note: I am using the OpenJDK build by Alexkasko.

回答1:

Since both PATH and JAVA_HOME are environment variables, you should be able to read both of their values in a similar way:

String javaHome = System.getenv("JAVA_HOME");
String path = System.getenv("PATH");


回答2:

Try

String javaHome = System.getProperty("java.home");


回答3:

Use System.getenv() to read the value.

 System.getenv("JAVA_HOME");


回答4:

You have to use System.getenv("JAVA_HOME");



回答5:

On windows you could execute the set command from you application as you would do in your cmd and afterwards handle the output:

Process p;
p = Runtime.getRuntime().exec("set JAVA_HOME");

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

But as answered by the others

System.getenv("JAVA_HOME");

would be the nicer way.

However if anyone needs an alternative, see above. :D