如何从Java设置环境变量? [英] How do I set environment variables from Java?

查看:148
本文介绍了如何从Java设置环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Java设置环境变量?我看到我可以使用 ProcessBuilder 。我有几个子进程要启动,所以我宁愿修改当前进程的环境,让子进程继承它。

How do I set environment variables from Java? I see that I can do this for subprocesses using ProcessBuilder. I have several subprocesses to start, though, so I'd rather modify the current process's environment and let the subprocesses inherit it.

有一个System.getenv(String)获取单个环境变量。我也可以使用System.getenv()获取一组完整的环境变量的映射。但是,在该Map上调用put()会抛出UnsupportedOperationException - 显然这意味着环境是只读的。而且没有System.setenv()。

There's a System.getenv(String) for getting a single environment variable. I can also get a Map of the complete set of environment variables with System.getenv(). But calling put() on that Map throws an UnsupportedOperationException -- apparently they mean for the environment to be read only. And there's no System.setenv().

那么,有没有办法在当前运行的进程中设置环境变量?如果是这样,怎么办?如果不是,理由是什么? (是因为这是Java,因此我不应该做恶意的不可移植的过时的事情,如触摸我的环境?)如果没有,任何好的建议,管理环境变量,我将需要喂养几个subprocesses?

So, is there any way to set environment variables in the currently running process? If so, how? If not, what's the rationale? (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?) And if not, any good suggestions for managing the environment variable changes that I'm going to need to be feeding to several subprocesses?

推荐答案


(是因为这是Java,因此我不应该做恶不便宜的过时的东西,如触摸我的环境?)

(Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?)

我想你打了头钉。

减轻负担的一种可能的方法是确定一个方法

A possible way to ease the burden would be to factor out a method

void setUpEnvironment(ProcessBuilder builder) {
    Map<String, String> env = builder.environment();
    // blah blah
}

并传递任何 ProcessBuilder 在启动它们之前。

and pass any ProcessBuilders through it before starting them.

此外,您可能已经知道这一点,但是您可以启动多个进程的ProcessBuilder 。所以如果你的子流程是一样的,你不需要一遍又一遍地这样做。

Also, you probably already know this, but you can start more than one process with the same ProcessBuilder. So if your subprocesses are the same, you don't need to do this setup over and over.

这篇关于如何从Java设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆