Get System Environment Variables using Java

Post date: Mar 25, 2011 11:46:47 AM

Many operating systems use environment variables to pass configuration information to applications. Like properties in the Java platform, environment variables are key/value pairs, where both the key and the value are strings. The conventions for setting and using environment variables vary between operating systems, and also between command line interpreters. To learn how to pass environment variables to applications on your system, refer to your system documentation.

Querying Environment Variables

On the Java platform, an application uses System.getEnv to retrieve environment variable values. Without an argument, getEnv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values. This is demonstrated in the EnvMap 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));         }     } }