Using export in Java

前端 未结 2 1835
野的像风
野的像风 2020-12-07 04:27

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

SOME_VARIABLE=/home/..
export SOME_VARIABLE


        
相关标签:
2条回答
  • 2020-12-07 05:09

    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 讨论(0)
  • 2020-12-07 05:10

    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);
    
    0 讨论(0)
提交回复
热议问题