203

如何获取系统变量值存在于

MyComputer -> Properties -> Advanced -> Environment Variables -> System Variables

在 Java 中?

编辑

我用过System.getenv()方法。

如果我给,它是印刷价值

System.out.println(System.getenv("JAVA_HOME"));

null如果我对我创建的系统变量尝试相同的操作,它就会显示价值

System.out.println(System.getenv("DBE"));
4

8 回答 8

232

使用System.getenv(String)方法,传递要读取的变量的名称。

于 2009-02-10T09:48:10.637 回答
57

为了澄清,系统变量与环境变量相同。用户环境变量是按用户设置的,并且在不同用户登录时会有所不同。无论用户登录,系统范围的环境变量都是相同的。

要在 Java 中访问系统范围变量或用户变量的当前值,请参见下文:

String javaHome = System.getenv("JAVA_HOME");

有关环境变量的更多信息,请参阅此维基百科页面

还要确保在调用 Java 之前正确设置了您尝试读取的环境变量,方法是:

echo %MYENVVAR%

您应该看到环境变量的值。如果没有,您可能需要重新打开 shell (DOS) 或注销并重新登录。

于 2009-02-10T10:26:14.320 回答
30

There are a few details of interest when getting system/environment properties.

First, System.getenv(String) was introduced way-back-when, then deprecated. The deprecation (foolishly, IHMO) continued all the way into JSE 1.4.

It got re-introduced in JSE 5.

Those are set using the Environment Variables panel in Windows. Changes to the variables may not get picked up until your current VM is shutdown, and the CMD.exe instance is exited.

In contrast to the environment properties, Java also has Java system properties, accessible through System.getProperties(). These variables can be initialized when the VM is started using a series -Dname=value command line arguments. For example, the values for the properties maxInMemory and pagingDirectory are set in the command below:

C:\> java.exe -DmaxInMemory=100M -DpagingDirectory=c:\temp -jar myApp.jar

These properties can be modified at runtime, barring security policy restrictions.

于 2009-02-11T09:50:05.263 回答
27

实际上变量可以设置或不设置,因此,在 Java 8 或更高版本中,它的可为空值应该被包装到一个Optional对象中,这样可以提供非常好的特性。在下面的示例中,我们将尝试获取变量ENV_VAR1,如果它不存在,我们可能会抛出一些自定义异常来警告它:

String ENV_VAR1 = Optional.ofNullable(System.getenv("ENV_VAR1")).orElseThrow(
  () -> new CustomException("ENV_VAR1 is not set in the environment"));
于 2016-06-17T14:51:30.730 回答
6

谷歌说要检查getenv()

返回当前系统环境的不可修改的字符串映射视图。

但是,我不确定系统变量与环境变量有何不同,因此,如果您能澄清一下,我可以提供更多帮助。

于 2009-02-10T09:49:47.963 回答
5

设置环境变量后,您是否尝试过重新启动?

似乎 Windows 将其环境变量保存在某种缓存中,重新启动是刷新它的一种方法。我不确定,但可能有不同的方法,但如果您不打算太频繁地更改变量值,这可能就足够了。

于 2009-02-10T13:13:08.543 回答
4

正如上面 sombody 所提到的,对于用户定义的环境变量,重新启动 eclipse 对我有用。在我重新启动 Eclipse IDE 后,System.getenv()正在获取我的环境变量。

于 2016-11-21T10:04:57.083 回答
1

你是linux系统吗?如果是这样,请确保您正在导出变量。

myVar=testvalue; export myVar

除非我使用 export 来全局定义值,否则我会得到 null。

于 2019-02-19T03:27:01.423 回答