Tuesday, March 6, 2012

How do I get Environment Variables in java?


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.

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);
        }
    }
}

Below is output..

ANT_HOME = D:\Development\apache-ant-1.6.5
CATALINA_HOME = D:\Development\apache-tomcat-5.5.15
ANT_OPS = -Djava.util.logging.config.file=logging.properties
CLASSPATH = .;C:\Program Files\Java\jre1.5.0_09\lib\ext\QTJava.zip
OC4J_HOME = D:\Development\oc4j-extended-101310
JAVA_HOME = D:\Development\Java\jdk1.5.0_09
GERONIMO_HOME = D:\Development\geronimo-1.0

No comments:

Post a Comment