简体   繁体   中英

How to set environment variable from java code and use this variable without restarting my workspace

I have a requirement where I need to run a command which needs an environment variable value to be present beforehand on Windows OS. I tried using

Process p = Runtime.getRuntime().exec("cmd.exe","/c","setx","ENVVAR","somevalue");
p=Runtime.getRuntime().exec("cmd.exe","/c","COMMANDTHATUSEENVAR");

Though this ENVVAR is set but the next command when runs give the error the ENVAR is not set. Now when I restart my workspace and run above code it happily takes the ENVAR value. But the problem is I cannot restart my workspace every time. So is there any possible solution where I get to set the environment variable and also use that value without restarting my workspace.

You could try the /V option, and try to built a single command, like the following example :

cmd /V /C "set EDITOR=vim&& echo !EDITOR!"

So my suggestion: first build a string that does what you need on the command line. Then translate that into something that works with the Java ProcessBuilder.

Alternatively: you could create a simple batch script that takes the ENVAR value as argument ; sets the ENVAR and then runs your tool.

In the end, your problem is that the ProcessBuilder will fork a new Process; so the "changes" that you make there are not visible when forking of another process later on. When you re-start your eclipse, that runs in a completely new process which sees those updates made by your first system call.

By default the environemnt block is copied from parent process to child process, but you can change the environment copy of the process you start.

public class EnvironmentTest
{
    public static void main(String[] args) throws Exception
    {
        ProcessBuilder pb = new ProcessBuilder(
            "CMD.exe"
            , "/C"
            , "start \"\" cmd /c \"set e & pause\""
        );
        pb.environment().put("ENVVAR", "This is a test");
        Process p = pb.start();
    }
}

The cmd instance started inside the ProcessBuilder has the environment variable defined. To show it, this instance is starting another one (the start "" cmd ... ) to show in screen the value in the variable.

Probably in your case you will need something like

public class EnvironmentTest
{
    public static void main(String[] args) throws Exception
    {
        ProcessBuilder pb = new ProcessBuilder(
            "CMD.exe"
            , "/C"
            , "start \"\" \"COMMANDTHATUSEEN‌​VAR\""
        );
        pb.environment().put("ENVVAR", "This is a test");
        Process p = pb.start();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM