Friday, May 09, 2008

Get Environment Variables in Java

In Java 1.5, to get the value of a single environment variable, you simply need to call the getEnv("environment variable") method providing the environment variable name that you want to evaluate. The following is a simple example:

String variable = System.getenv("PATH");
System.out.println(variable);

In Java 1.5, a new method was introduced to allow you to discover all of the environment variables defined in the system. The following example uses the new method to print all of the environment variables and their values:

Map variables = System.getenv();for (Map.Entry entry : variables.entrySet()){ String name = entry.getKey(); String value = entry.getValue(); System.out.println(name + "=" + value);}

That's it.

No comments: