我们可以在 Java 中读取操作系统环境变量吗?

Can we read the OS environment variables in Java?(我们可以在 Java 中读取操作系统环境变量吗?)
本文介绍了我们可以在 Java 中读取操作系统环境变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的操作系统是 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 中读取操作系统环境变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)