3

I am using java to call another program which relies on an exported environment variable to function:

SOME_VARIABLE=/home/..
export SOME_VARIABLE

How can I use java to set this variable, so that I can use this program on more than just one machine? Essentially I want to be able to emulate the above commands via java.

Neutralise
  • 309
  • 5
  • 12
  • 1
    You may also want to check out this SO post: http://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java – JW8 Sep 10 '11 at 04:48
  • How are you calling the other program and is that Java or something else? – Vishal Sep 10 '11 at 05:51

2 Answers2

7

You can set environment variables when using java.lang.Runtime.getRuntime().exec(...) or java.lang.Processbuilder to call the other program.

With Processbuilder, you can do:

ProcessBuilder processBuilder = new ProcessBuilder("your command");
processBuilder.environment().put("SOME_VARIABLE", "/home/..");
processBuilder.start();

With Runtime, it's:

Map<String, String> environment = new HashMap<String, String>(System.getenv());
environment.put("SOME_VARIABLE", "/home/..");
String[] envp = new String[environment.size()];
int count = 0;
for (Map.Entry<String, String> entry : environment.entrySet()) {
    envp[count++] = entry.getKey() + "=" + entry.getValue();
}

Runtime.getRuntime().exec("your command", envp);
Ingo Kegel
  • 46,523
  • 10
  • 71
  • 102
  • Nice work, especially treating the environment has a hashmap, rather than blindly adding variables to the end of the array. – tresf Mar 23 '16 at 16:17
1

Perhaps you can use System#setProperty(String property, String value), though I'm not sure if this will change anything outside of the current JVM, which means this environment variable will only be available to processes that the current JVM starts.

Nate W.
  • 9,141
  • 6
  • 43
  • 65