我们可以在 Java 中读取操作系统环境变量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20610080/
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
Can we read the OS environment variables in Java?
提问by William
My OS is windows7. I want to read the environment variables in my Java application. I have searched google and many people's answer is to use the method System.getProperty(String name)
or System.getenv(String name)
. But it doesn't seem to work. Through the method, I can read some variable's value that defined in the JVM.
我的操作系统是windows7。我想在我的 Java 应用程序中读取环境变量。我在google上搜索过,很多人的答案是使用方法 System.getProperty(String name)
或 System.getenv(String name)
。但它似乎不起作用。通过该方法,我可以读取JVM中定义的一些变量的值。
If I set an environment variable named "Config", with value "some config information", how can I get the value in Java?
如果我设置了一个名为“Config”的环境变量,值为“一些配置信息”,我如何在 Java 中获取该值?
采纳答案by Dror Bereznitsky
You should use System.getenv(), for example:
您应该使用System.getenv(),例如:
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
When running from an IDE you can define additional environment variable which will be passed to your Java application. For example in IntelliJ IDEA you can add environment variables in the "Environment variables" field of the run configuration.
从 IDE 运行时,您可以定义将传递给 Java 应用程序的附加环境变量。例如,在 IntelliJ IDEA 中,您可以在运行配置的“环境变量”字段中添加环境变量。
Notice (as mentioned in the comment by @vikingsteve) that the JVM, like any other Windows executable, system-level changes to the environment variables are only propagated to the process when it is restarted.
For more information take a look at the "Environment Variables" section of the Java tutorial.System.getProperty(String name)
is intended for getting Java system propertieswhich are not environment variables.
请注意(如@vikingsteve 的评论中所述),JVM 与任何其他 Windows 可执行文件一样,对环境变量的系统级更改仅在重新启动时传播到进程。
有关更多信息,请查看Java 教程的“环境变量”部分。System.getProperty(String name)
用于获取不是环境变量的Java系统属性。
回答by enderland
In case anyone is coming here and wondering how to get a specific environment variable without looping through all of your system variables you can use getenv(String name)
. It returns "the string value of the variable, or null if the variable is not defined in the system environment".
如果有人来到这里并想知道如何在不遍历您可以使用的所有系统变量的情况下获取特定的环境变量getenv(String name)
。它返回“变量的字符串值,如果变量未在系统环境中定义,则返回 null”。
String myEnv = System.getenv("env_name");