1

我有一个使用 System.getenv("MY_VAR") 获取系统环境变量的 JAVA 应用程序。有没有办法只搜索 Windows 系统环境变量而不是用户环境变量,类似于我们如何将环境变量目标传递给 C# Environment.GetEnvironmentVariable() 方法?任何帮助,将不胜感激。谢谢!

4

2 回答 2

1

There is no way to do that in Java, at least not natively (see below).

Windows merges system and user environment variables and passes the merged environment to applications, with no information about where each specific variable came from. C# can do it because C# does it not by accessing the process's environment, but instead accessing system environment configuration directly in the registry. Hence, it can make that distinction. Java only gives you direct access to the equivalent of the Process environment target in C#.

Now, if you're really desperate, you could read the values from the Windows registry just as C# does. The problem is that Java does not give direct access to the registry, you can only access a limited subset of registry keys through the Preferences API. For full access you need to use JNI.

There is a JNI registry library at http://www.trustice.com/java/jnireg/. You can use this to read the same registry keys that C# uses and access the same data.

The take home point here is that C# gives you access to that info not through the actual environment block, but by reading system settings directly, which Java cannot do natively.

于 2013-08-14T23:22:29.277 回答
0

By the time your process receives the environment, it has all been merged into a single list of key/value pairs. The separation into System and User variables is a Windows-only subtlety that does not propagate down to programs... unless you write non-portable code to read the Windows registry directly.

于 2013-08-14T23:21:30.257 回答