How to enumerate all environment variable in Java

2019-04-03 12:15发布

问题:

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?

回答1:

System.getenv() will return a Map<String,String> with all of the environment variables.

But you could just as easily switch to ProcessBuilder which is a more convenient API to start new processes.

With ProcessBuilder you can simply call environment() and get a Map that contains existing environment variables and which you can manipulate how you want: i.e., if you add something to it, then that will be added to the new processes environment variables. If you remove something from it, it will not be present in the new process.



回答2:

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


回答3:

If you run an external shell, you can use it to set environment variables. e.g.

bash -c ENV1=hi ENV2=bye echo $ENV1 $ENV2

This only works if you have a UNIX shell (or cygwin)

You should migrate away from Java 1.4 and Java 5.0. Even Java 6 you might consider upgrading to Java 7.