问题描述
我的操作系统是 windows7.我想在我的 Java 应用程序中读取环境变量.我搜索了谷歌,很多人的答案是使用方法 System.getProperty(String name)
或 System.getenv(String name)
.但这似乎不起作用.通过该方法,我可以读取在 JVM 中定义的一些变量的值.
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.
如果我设置了一个名为Config"的环境变量,其值为some config information",如何在Java中获取该值?
If I set an environment variable named "Config", with value "some config information", how can I get the value in Java?
推荐答案
你应该使用 System.getenv(),例如:
You should use System.getenv(), for example:
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));
}
}
}
从 IDE 运行时,您可以定义其他环境变量,该变量将传递给您的 Java 应用程序.例如,在 IntelliJ IDEA 中,您可以在 run 的环境变量"字段中添加环境变量配置.
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.
请注意(正如@vikingsteve 的评论中所提到的)JVM 与任何其他 Windows 可执行文件一样,对环境变量的系统级更改仅在重新启动时传播到进程.
有关更多信息,请查看 Java 教程的环境变量"部分.System.getProperty(String name)
用于获取 Java 系统属性 不是环境变量.
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 properties which are not environment variables.
这篇关于我们可以在 Java 中读取操作系统环境变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!