Can we read the OS environment variables in Java?

前端 未结 2 1369
夕颜
夕颜 2020-11-28 13:05

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.getP

2条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 14:01

    You should use System.getenv(), for example:

    import java.util.Map;
    
    public class EnvMap {
        public static void main (String[] args) {
            Map 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.

提交回复
热议问题