开发者

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_V开发者_JAVA百科ARIABLE

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜