Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we read the OS environment variables in Java?

My OS is windows7. I want to read the environment variables in my Java application. I have searched google and many people's answer is to use the method System.getProperty(String name) or System.getenv(String name). But it doesn't seem to work. Through the method, I can read some variable's value that defined in the JVM.

If I set an environment variable named "Config", with value "some config information", how can I get the value in Java?

like image 367
William Avatar asked Dec 16 '13 11:12

William


People also ask

How do you read an environment variable in Java?

How to get the value of Environment variables? The System class in Java provides a method named System. getenv() which can be used to get the value of an environment variable set in the current system.

How do I access system environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.

How do I read all environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

Where are OS environ variables stored?

Your environment variables are now stored in your . env file.


2 Answers

You should use System.getenv(), for example:

import java.util.Map;  public class EnvMap {     public static void main (String[] args) {         Map<String, String> env = System.getenv();         for (String envName : env.keySet()) {             System.out.format("%s=%s%n",                               envName,                               env.get(envName));         }     } } 

When running from an IDE you can define additional environment variable which will be passed to your Java application. For example in IntelliJ IDEA you can add environment variables in the "Environment variables" field of the run configuration.

Notice (as mentioned in the comment by @vikingsteve) that the JVM, like any other Windows executable, system-level changes to the environment variables are only propagated to the process when it is restarted.

For more information take a look at the "Environment Variables" section of the Java tutorial.

System.getProperty(String name) is intended for getting Java system properties which are not environment variables.

like image 84
Dror Bereznitsky Avatar answered Sep 20 '22 12:09

Dror Bereznitsky


In case anyone is coming here and wondering how to get a specific environment variable without looping through all of your system variables you can use getenv(String name). It returns "the string value of the variable, or null if the variable is not defined in the system environment".

String myEnv = System.getenv("env_name"); 
like image 35
enderland Avatar answered Sep 19 '22 12:09

enderland