set windows PATH environment variable at runtime in Java

hhhh picture hhhh · Apr 30, 2010 · Viewed 19.6k times · Source

I have a java program that fires off an executable using the Runtime.exec() method. I'm using the variant that takes in a set of command line params as one argument, and some environment variables as another argument.

The environment variable I'm tryign to set is path, so i'm passing in "PATH=C:\some\path". This does not work. Is there some trick to this or any alternatives. I am stuck to Java 1.4 unfortunately.

Answer

Ray Tayek picture Ray Tayek · Apr 30, 2010

Use getenv to get the environment and fix it up then use a flavour of exec to do the exec.

This works with a batch file that has path in it.

package p;

import java.util.*;

public class Run {
    static String[] mapToStringArray(Map<String, String> map) {
        final String[] strings = new String[map.size()];
        int i = 0;
        for (Map.Entry<String, String> e : map.entrySet()) {
            strings[i] = e.getKey() + '=' + e.getValue();
            i++;
        }
        return strings;
    }

    public static void main(String[] arguments) throws Exception {
        final Map<String, String> env = new HashMap<String, String>(System.getenv());
        env.put("Path", env.get("Path") + ";foo");
        final String[] strings=mapToStringArray(env);
        Runtime.getRuntime().exec("cmd /C start foo.bat",strings);
    }

}