How to enumerate all environment variable in Java

左心房为你撑大大i 提交于 2019-12-03 22:21:53
Joachim Sauer

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.

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

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.

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