简体   繁体   English

如何获取Java环境中被用户环境变量覆盖的系统环境变量?

[英]How to get a system environmental variable that is overridden by a user environmental variable in Java?

In a windows 7 environment, I have a variable VARA="x" defined under System's enironmental variables and the same variable VARA="y" defined under the user's environmental variables. 在Windows 7环境中,我在System的环境变量下定义了一个变量VARA =“ x”,而在用户的环境变量下定义了一个变量VARA =“ y”。 how do i get the value of VARA as defined in the system's environmental variables section. 如何获得系统环境变量部分中定义的VARA值。 I always get the user value not the system one. 我总是得到用户价值而不是系统价值。 Thanks. 谢谢。

You can't. 你不能

System.getenv() returns the value of the environment variables at the time your app launched. System.getenv()返回启动应用程序时环境变量的值。 How those values were set is irrelevant and inaccessible to the JVM 这些值的设置方式与JVM无关且不可访问

You'll have to access the registry using JNA . 您必须使用JNA访问注册表

Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,
    "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",
    name);

You can also access user variables: 您还可以访问用户变量:

Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER,
    "Environment",
    name);

In Java you just type: 在Java中,您只需键入:

 String variable = System.getenv("WINDIR");  
System.out.println(variable); 

and you get the system's environmental variable. 您会得到系统的环境变量。

If you want to search for all system's environmental variables: 如果要搜索所有系统的环境变量:

Map<String, String> variables = System.getenv();  

for (Map.Entry<String, String> entry : variables.entrySet())  
{  
   String name = entry.getKey();  
   String value = entry.getValue();  
   System.out.println(name + "=" + value);  
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JAVA中如何设置System.getenv(&quot;name&quot;)可以获取的环境变量 - How to set environmental variable that can be get by System.getenv("name") in JAVA Java没有接受环境变量 - Java not picking up on environmental variable karaf-如何在system.properties文件中添加环境变量 - karaf - how to add environmental variable in system.properties file 如何在Java中使用CLASSPATH环境变量指定依赖于applet的jar - How to specify applet dependent jars using CLASSPATH environmental variable in java Java环境变量的困境,Maven也 - Java environmental variable woes, maven also DrJava设置环境变量 - DrJava set environmental variable Android Studio抱怨我的JAVA环境变量 - Android studio complains about my JAVA environmental variable 适用于 Linux 的 Windows 子系统无法识别 JAVA_HOME 环境变量 - Windows Subsystem for Linux not recognizing JAVA_HOME Environmental Variable Micronaut @Value 在运行原生镜像时没有获取环境变量 - Micronaut @Value does not get the environmental variable when running native image 如何在上下文文件中将字符串数组定义为环境参数/变量? - How to define an array of strings as an environmental parameter/variable in the context-file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM