Friday, May 4, 2007

Reading Windows Environment Variables from Java

Environment variables can be simply described as user-defined name/value pairs. An example entry would take the form of "APP_ENV=dev".

For a complete overview of environment variables for MS Windows, refer to the following link: (http://support.microsoft.com/kb/310519) How To Manage Environment Variables in Windows XP.

In Java, you can send the complete contents of the environment variables to the console using the following method:



/**
*
*
*/
public static void dumpEnvironmentVariables() {

Map variables = System.getenv();
Set variableNames = variables.keySet();
Iterator nameIterator = variableNames.iterator();

System.out.println("===============================================================");
System.out.println("System Environment variables");

for (int index = 0; index < variableNames.size(); index++) {
String name = (String) nameIterator.next();
String value = (String) variables.get(name);
System.out.println(" " + name + "=" + value);
}

}



Running this method should produce a list similar to that shown below:




===============================================================
System Environment variables
CATALINA_HOME=C:\TomcatInstalls\apache-tomcat-5.5.20
HOMEDRIVE=C:
windir=C:\WINDOWS
SystemDrive=C:
ProgramFiles=C:\Program Files
APP_ENV=dev
.
.
.





Environment variables are commonly used to control application behavior or to provide a resource location using a directory path. For developing Java applications, this can be a good way to control the program's behavior during development where certain features or processes should not be allowed to execute. This can be done by interrogating the value established by an environment variable such as "APP_ENV=dev".

You can also read a specific environment variable simply by providing the name of the variable using a method like this one:



/**
* Accepts a string representing the key-name to a named environment variable.
* Environment variables for Windows can be established using the following steps:
*
* Start-> Settings-> System-> Advanced Tab-> Environment Variables button->
* Under System Variables, New button-> and add the name/value pair.
*
* @param name
* @return
*/
public static String getEnvVariable(String name) {
String value = null;

variables = System.getenv();
variableNames = variables.keySet();

return (String)variables.get(name);
}

No comments: