How to add environment variable from java code

130 Views Asked by At

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

There are 1 best solutions below

0
On

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().