英文:
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("CMD", "/C", "SET");
Map<String, String> envMap = pb.environment();
envMap.put("PGPASSWORD", 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()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论