java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to get Environment Variables?

Environment variables are sets of dynamic values that can affect a running process, such as our Java program. Each process usually have there own copy of these variables.

Now we'd like to obtain the available variables in our environment or operating system, how do I do this in Java? Here is a code example of it.

package com.javacoderanch.sample.java.lang;
 
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
 
public class SystemEnv
{
    public static void main(String[] args)
    {
        // We get the environment information from the System class. 
        // The getenv method (why shouldn't it called getEnv()?) 
        // returns a map that will never have null keys or values 
        // returned.
        Map map = System.getenv();
 
        // For this purpose of example we will interate the keys and 
        // values in it so we create an iterator object from it.
        Set keys = map.keySet();
        Iterator iterator = keys.iterator();
        while (iterator.hasNext())
        {
            // Here we iterate based on the keys inside the map, and 
            // with the key in hand we can get it values.
            String key = (String) iterator.next();
            String value = (String) map.get(key);
 
            System.out.println(key + " = " + value);
        }
    }
}

Here are some result on my machine.

ANT_HOME = D:Developmentapache-ant-1.6.5
CATALINA_HOME = D:Developmentapache-tomcat-5.5.15
ANT_OPS = -Djava.util.logging.config.file=logging.properties
CLASSPATH = .;C:Program FilesJavajre1.5.0_09libextQTJava.zip
OC4J_HOME = D:Developmentoc4j-extended-101310
JAVA_HOME = D:DevelopmentJavajdk1.5.0_09
GERONIMO_HOME = D:Developmentgeronimo-1.0