Friday, August 10, 2007

How to get user defined environment variable in Java

I'm porting a C++ library over to Java 1.4.2 and I need to get the setting for a user defined environment variable. There used to be a very easy way, but it turns out some brilliant people decided to deprecate - get rid of - System.getenv for java 1.4. There must have been complaints because for Java 1.5 System.getenv is undeprecated. Unfortunately, I can't guarantee the users of my java software will be using java 1.5. Fortunately, there are people much smarter than I. I did some searching and found a website with some code which determines what system you are on and then calls the corresponding function to get all environment variables. You can then make a call to get the value of the environment variable you need. Here's the link to the site and the code itself:

import java.io.*;
import java.util.*;

public class ReadEnv {
public static Properties getEnvVars() throws Throwable {
Process p = null;
Properties envVars = new Properties();
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
// System.out.println(OS);
if (OS.indexOf("windows 9") > -1) {
p = r.exec( "command.com /c set" );
}
else if ( (OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 2000") > -1 )
|| (OS.indexOf("windows xp") > -1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set" );
}
else {
// our last hope, we assume Unix (thanks to H. Ware for the fix)
p = r.exec( "env" );
}
BufferedReader br = new BufferedReader
( new InputStreamReader( p.getInputStream() ) );
String line;
while( (line = br.readLine()) != null ) {
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
envVars.setProperty( key, value );
// System.out.println( key + " = " + value );
}
return envVars;
}

public static void main(String args[]) {
try {
Properties p = ReadEnv.getEnvVars();
System.out.println("the current value of TEMP is : " +
p.getProperty("TEMP"));
}
catch (Throwable e) {
e.printStackTrace();
}
}
}



Java Resources

No comments: