从 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
Checking/getting JAVA_HOME Variable from Java
提问by antonio
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:
在 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
回答by Andrea Boscolo
You have to use System.getenv("JAVA_HOME");
你必须使用 System.getenv("JAVA_HOME");
回答by das Keks
On windows you could execute the set
command 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