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

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

问题描述

如何从 Java 设置环境变量?我看到我可以使用 为子进程执行此操作进程构建器.不过,我有几个子进程要启动,所以我宁愿修改当前进程的环境,让子进程继承它.

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.但是,在那个 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,因此我不应该做一些邪恶的不可移植的过时的事情,比如触摸我的环境?)如果不是,我将需要提供给几个管理环境变量更改的好建议子流程?

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?)

我想你已经一针见血了.

I think you've hit the nail on the head.

减轻负担的一种可能方法是找出一种方法

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天全站免登陆