How to set an environment variable in Java using exec?

Jimmy picture Jimmy · Dec 22, 2011 · Viewed 32.8k times · Source

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?

Answer

sudocode picture sudocode · Dec 22, 2011

There are overloaded exec methods in which you can include an array of environment variables. For example exec(String command, String[] envp).

Here's an example (with proof) of setting an env variable in a child process you exec:

public static void main(String[] args) throws IOException {

    String[] command = { "cmd", "/C", "echo FOO: %FOO%" };
    String[] envp = { "FOO=false" };

    Process p = Runtime.getRuntime().exec(command, envp);
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String s = reader.readLine();
    System.err.println(s);
}

However, that sets the variable in the env of the created process, not of your current (Java) process.

Similarly, if you are creating a process from Ant (as you mention in comments to aix) using the exec task, then you can pass environment variables to the child process using nested env elements, e.g.

<exec executable="whatever">
   <env key="FOO" value="false"/>
</exec>