Reputation: 547
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?
Upvotes: 5
Views: 11144
Reputation: 1
Seelenvirtuose is right. You need to write the name of the SYSTEM environment variable using quotes:
String serverUrl = System.getenv("QNAP-NAS-ADDRESS");
private String jdbcURL = "jdbc:mysql://" + serverUrl + "schema_name?useSSL=false";
private String jdbcUsername = System.getenv("QNAP-MYSQL-UN");
private String jdbcPassword = System.getenv("QNAP-MYSQL-UN");
Printing these:
System.out.println(System.getenv("QNAP-MYSQL-UN"));
System.out.println(System.getenv("QNAP-MYSQL-PW"));
System.out.println(System.getenv("QNAP-NAS-ADDRESS"));
System.out.println(System.getenv("QNAP-NOIP-ADDRESS"));
would display in terminal:
root
password
mynasserver.myqnapcloud.com
mynasserver.ddns.net
I didn't use USER VARIABLES, but SYSTEM VARIABLES.
@Seelenvirtuose Thanks, btw
Upvotes: 0
Reputation: 1
You can get the value of a USER environment variables, by reading the registry key in the path: HKEY_CURRENT_USER\\Environment
There you will find all the USER environment variables added.
and for the SYSTEM environment variables you can read in the path:
HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment
Upvotes: -2
Reputation: 20618
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.
Upvotes: 13
Reputation: 201447
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).
Upvotes: 1