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.

2
  • I have tried it. It's not working as per my requirement. Commented Oct 11, 2019 at 6:46
  • You can't set the system environment using java, although you can set it which last till the current process is running. Commented Oct 11, 2019 at 7:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.