How to enumerate all environment variable in Java

sevenever picture sevenever · Sep 15, 2011 · Viewed 34k times · Source

System.getenv(name) needs the name of environment variable.

I am trying to call Runtime.exec(String[], String[], File), the secondary parameter need an array of environment variable, I am not sure whether subprocess will inherit environment variables from current process if I specified this parameter.

For example, if I pass new String[]{"NEWDIR=/home"} as secondary parameter and current java process has environment OLDDIR=/var, what is the return value of System.getenv("OLDDIR") in the subprocess?

updated: Sorry, I have to use Java 1.4 and it seems that System.getenv() was introduced in 1.5?

Answer

stacker picture stacker · Sep 15, 2011
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
    System.out.format("%s=%s%n", envName, env.get(envName));
}