Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User environment variable in java

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?

like image 349
user3469203 Avatar asked May 12 '14 13:05

user3469203


2 Answers

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).

like image 32
Elliott Frisch Avatar answered Sep 17 '22 13:09

Elliott Frisch


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.

like image 127
Seelenvirtuose Avatar answered Sep 16 '22 13:09

Seelenvirtuose