What is the best/foolproof way to get the values of environment variables in Windows when using J2SE 1.4 ?
You have definitely no way to access environment variables straigthly from java API. The only way to achieve that with Runtime.exec with such a code :
Process p = null;
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" );
}
Although you can access Java variables thanks to System.getProperties(); But you would only get some env variables mapped by JVM itself, and additional data you could provide on java command line with "-Dkey=value"
For more information see http://www.rgagnon.com/javadetails/java-0150.html
Pass them into the JVM as -D system properties, for example:
java -D<java var>=%<environment var>%
That way you don't become tied to a particular OS.
There's a switch to the JVM for this. From here:
Start the JVM with the "-D" switch to pass properties to the application and read them with the System.getProperty() method.
SET myvar=Hello world
SET myothervar=nothing
java -Dmyvar="%myvar%" -Dmyothervar="%myothervar%" myClass
then in myClass
String myvar = System.getProperty("myvar");
String myothervar = System.getProperty("myothervar");
You can use getEnv() to get environment variables:
String variable = System.getenv("WINDIR");
System.out.println(variable);
I believe the getEnv() function was deprecated at some point but then "undeprecated" later in java 1.5
ETA:
I see the question now refers specifically to java 1.4, so this wouldn't work for you (or at least you might end up with a deprecation warning). I'll leave the answer here though in case someone else stumbles across this question and is using a later version.