How to enumerate all environment variable in Java

可紊 提交于 2019-12-05 09:50:38

问题


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.



来源:https://stackoverflow.com/questions/7427109/how-to-enumerate-all-environment-variable-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!