Neutralise
Neutralise

Reputation: 329

Using export in Java

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.

Upvotes: 3

Views: 8931

Answers (2)

Ingo Kegel
Ingo Kegel

Reputation: 48015

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);

Upvotes: 7

Nate W.
Nate W.

Reputation: 9249

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.

Upvotes: 1

Related Questions