如何从Java代码中添加环境变量

huangapple go评论126阅读模式
英文:

How to add environment variable from java code

问题

想要从我的Java应用程序中添加"PGPASSWORD"环境变量。

我知道可以使用以下方式添加。

private void setPgPasswordEnv(String pwdValue) {
    ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "SET");
    Map<String, String> envMap = pb.environment();
    envMap.put("PGPASSWORD", pwdValue);
}

如果我们使用上述方法添加,它会在我的应用程序运行期间保持有效吗?

从Java添加环境变量是否有更好的方法?

英文:

Want to add "PGPASSWORD" env variable from my java application.

I know using below way, we can add.

private void setPgPasswordEnv(String pwdValue) {

	ProcessBuilder pb = new ProcessBuilder(&quot;CMD&quot;, &quot;/C&quot;, &quot;SET&quot;);

	Map&lt;String, String&gt; envMap = pb.environment();

	envMap.put(&quot;PGPASSWORD&quot;, pwdValue);
} 

If we add using above, will it persist till my application runs?

Is there any best way to add env variable from java?

答案1

得分: 1

如果您执行该代码,则会应用于运行CMD程序的新进程,随后当您调用pb.start()时。

它不会影响正在运行的Java程序,也不会影响任何其他ProcessBuilder,因为每个ProcessBuilder都有自己的环境变量副本,用于设置新进程的环境变量。

正如在文档详细解释的那样,即environment()的javadoc。

英文:

If you do that code, it applies to the new process(es) running the CMD program, when you subsequently call pb.start().

It does not affect the running Java program, and it does not affect any other ProcessBuilder, since each ProcessBuilder has it's own copy of the environment variables to set for the new process(es).

As fully explained in the documentation, i.e. the javadoc of environment().

huangapple
  • 本文由 发表于 2020年4月9日 15:30:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/61116035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定