从 Java 检查/获取 JAVA_HOME 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16297326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:32:27  来源:igfitidea点击:

Checking/getting JAVA_HOME Variable from Java

javaopenjdkjava-home

提问by antonio

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

在 Java 程序中,如何读取JAVA_HOME变量(确保以正确的方式设置)?同样,如何获取bin文件夹的路径?也就是说,通常通过以下方式在 Windows 中设置路径:

path %path%;%JAVA_HOME%\bin

path %path%;%JAVA_HOME%\bin

Note: I am using the OpenJDK build by Alexkasko.

注意:我使用的是Alexkasko的 OpenJDK 版本。

回答by Thilo

Try

尝试

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

回答by David

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

由于 PATH 和 JAVA_HOME 都是环境变量,您应该能够以类似的方式读取它们的值:

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

回答by NINCOMPOOP

Use System.getenv()to read the value.

使用System.getenv()读取值。

 System.getenv("JAVA_HOME");

回答by Andrea Boscolo

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

你必须使用 System.getenv("JAVA_HOME");

回答by das Keks

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

在 Windows 上,您可以set像在 cmd 中一样从应用程序执行命令,然后处理输出:

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

但是,如果有人需要替代方案,请参见上文。:D