Java中如何枚举所有环境变量
System.getenv(name)
需要环境变量的名称。
我正在尝试调用 Runtime.exec(String[], String[], File), 辅助参数需要一个环境变量数组,我不确定子进程是否会从当前进程继承环境变量如果我指定这个参数。
例如,如果我传递 new String[]{"NEWDIR=/home"}
作为辅助参数,并且当前 java 进程具有环境 OLDDIR=/var
,则返回是什么子进程中 System.getenv("OLDDIR")
的值?
更新: 抱歉,我必须使用 Java 1.4,而且 System.getenv()
似乎是在 1.5 中引入的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
System.getenv( )
将返回包含所有环境变量的Map
。但是您可以轻松切换到
ProcessBuilder< /code>
这是一个更方便的 API 来启动新进程。
使用 ProcessBuilder,您可以简单地调用
environment()
并获取一个包含现有环境变量的Map
,您可以操纵你想要的方式:即,如果你向其中添加一些内容,然后将其添加到新进程的环境变量中。如果您从中删除某些内容,它将不会出现在新进程中。System.getenv()
will return aMap<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 callenvironment()
and get aMap
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.如果运行外部 shell,则可以使用它来设置环境变量。例如,
这仅在您有 UNIX shell(或 cygwin)时才有效。
您应该从 Java 1.4 和 Java 5.0 迁移出去。即使是 Java 6,您也可能会考虑升级到 Java 7。
If you run an external shell, you can use it to set environment variables. e.g.
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.