我们可以在Java中阅读OS环境变量吗? [英] Can we read the OS environment variables in Java?

查看:122
本文介绍了我们可以在Java中阅读OS环境变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的os是windows7。我想在我的Java应用程序中读取环境变量。我搜索过google,很多人的答案是使用方法 System.getProperty(String name) System.getenv(String name)。但它似乎不起作用通过该方法,我可以读取JVM中定义的一些变量的值。



如果我设置一个名为Config的环境变量,值为一些配置信息,那么如何在Java中获取该值?



感谢任何帮助!

解决方案

你应该使用 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));
}
}
}

从IDE运行时可以定义将传递给您的Java应用程序的其他环境变量。例如,在IntelliJ IDEA中,您可以在运行中的环境变量字段中添加环境变量配置



注意(如@vikingsteve的评论中所述),JVM与任何其他Windows可执行文件一样,系统级更改为环境变量只会在重新启动时传播到进程。


有关更多信息,请查看环境变量部分的Java教程。


System.getProperty(String name)旨在获取不是环境变量的Java 系统属性


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.

If I set an environment variable named "Config", with value "some config infomations", how can I get the value in Java?

Thanks for any help!

解决方案

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));
        }
    }
}

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.

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中阅读OS环境变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆