I am trying to get a user environment variable in java.
The System.getEnv()
method only return system environment variables.
Does anybody know how to get user environment variables?
System.getenv(String) is the correct method; there are only "environment variables" - Windows applies the "system" environment variables to everyone's account, but they aren't differentiable at the application level. You can verify by opening a cmd
prompt and executing set
(with no arguments).
When running a process there is only one environment. The user variables are merged into the system variables, with overwriting existing ones. This complete environment is then retrieved by the System.getenv()
method.
So you actually see the user's environment variables.
I just tested it with these four scenarios:
1) No variable named MYVAR
:
Running System.out.println(System.getenv("MYVAR"))
prints out null
.
2) System variable called MYVAR
with value System
:
Running System.out.println(System.getenv("MYVAR"))
prints out System
.
3) User variable called MYVAR
with value User
:
Running System.out.println(System.getenv("MYVAR"))
prints out User
.
4) System variable called MYVAR
with value System
and user variable called MYVAR
with value User
:
Running System.out.println(System.getenv("MYVAR"))
prints out User
.
Maybe you did try it out from an IDE (like Eclipse)? When changing the environment variables, you unfortunately have to restart Eclipse, as they are not correctly propagated to the run configurations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With