0

I want to set environment variable in JAVA . For this , I have searched a lot in internet and got the following code

ProcessBuilder pb = new ProcessBuilder();
Map<String, String> env = pb.environment();
env.put("DS_HOME", "C:\\MyFile\\jboss-eap-6.4\\modules\\com\\mycom\\library\\d_home");
env.put("CS_HOME", "C:\\MyFile\\jboss-eap-6.4\\modules\\com\\mycom\\library\\c_home");
pb.command("cmd.exe", "/c", "echo", "%DS_HOME%");
pb.command("cmd.exe", "/c", "echo", "%CS_HOME%");
try {
    pb.inheritIO().start();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Map<String, String> getenv = System.getenv();
Set<Entry<String,String>> entrySet = getenv.entrySet();
for (Entry<String, String> entry : entrySet) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}

After Executing this code, i am not getting the custom variables which i have set using ProcessBuilder. Please help me out to solve this. I want to execute a service which needs some environments variables and to i am trying to set the system varibales using java code.

Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
Parul
  • 1
  • 1
  • 2

2 Answers2

1

Strong suggestion:

Your best bet is probably to:

  1. Write a .bat file that: a) Sets your environment variables, then b) calls your .exe

  2. Have your Java program invoke the .bat file

For whatever it's worth, here's how you'd change Windows system environment variables from C or C++ using Win32 APIs:

https://learn.microsoft.com/en-us/windows/win32/procthread/environment-variables

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

If you want to alter system variables for your current Java process, you will have to go via JNI

Settings environment variable inside JVM via JNI https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo043

Oo.oO
  • 12,464
  • 3
  • 23
  • 45