Search code examples
javaenvironment-variablesruntime.execjava-6

How to set an environment variable in Java using exec?


Possible Duplicate:
How do I set environment variables from Java?

I'm trying to set an environment variable, and read it back to verify it was actually set.

I've got the following :

import java.io.IOException;

public class EnvironmentVariable
{
    public static void main(String[] args) throws IOException
    {
        Runtime.getRuntime().exec("cmd.exe set FOO=false");

        String s = System.getenv("FOO");
        System.out.println(s);
    }
}

However, it appears that FOO is always null, meaning its probably not set correctly.

Do I have the exec command correct? The javadocs state it can take a string argument as the command.

Any ideas?


Solution

  • This won't work. When you start a new process, that process receives a copy of the environment. Any changes it then makes to environment variables are made within that copy, and at no point will become visible to the caller.

    What are you actually trying to achieve?