Discussion Locked

How Java Reads OS Env Variables ?

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I am using JDK 1.3 right now. Before that I used to use System.getenv to retrieve OS env var. But getenv in 1.3 is deprecated. Is there other way to read env var ? I understand that properties file or even LDAP is the latest preferred way. But my system need to share the same env var with other concurrent systems, e.g. ApplEnv=uat ...etc.

Thanks.
Jim

3 replies

by okujava

try System.getProperty("myVar")

to see all vars, try:

Properties props = System.getProperties();
Enumeration enum = props.keys();
while(enum.hasMoreElements()){
String key = (String)enum.nextElement();
System.out.println(key + "\t\t" +props.get(key));
}

s.okujava

by shanghai sam

No, that doesn't work.

E.g. System.getProperty("ComSpec") will return a null. (under Win2k)

And the program sample only list the predefined variables in JVM, not OS level, or any user defined env variables.

Jim

by jim lai

I turn out used a tricky way to resolve this. See the example below. It forks a system command (depends on OS architecture) to echo back the value. Then I can read the env variable content from the output. Anyway, it is not good way but it solves the problem.

Runtime rt = Runtime.getRuntime();
Process p;
InputStream is;
int j;
byte outbyte[] = new byte[1024];
String outline;

try {
if (System.getProperty("os.arch").equals("x86")) {
p = rt.exec("cmd /c echo %AA_HOME%"); // For Windows
} else {
p = rt.exec( "myGetEnv.ksh AA_HOME" ); // For Unix
}
p.waitFor();
is = p.getInputStream();

j = is.read( outbyte, 0, outbyte.length );

outline = new String( outbyte, 0, j ).trim();
System.out.println( "AA_HOME=" + outline );

} catch (Exception e) {
e.printStackTrace();
}

BTW, somehow I can't just put a "echo $AA_HOME" or "sh -c \"echo $AA_HOME\"" in the UNIX clause. Can someone help ?

Thanks.
Jim

This discussion is closed to new replies.