Java – How to enumerate all environment variable in Java

environmentjava

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?

Best Answer

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