Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

set windows PATH environment variable at runtime in Java

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:somepath". This does not work. Is there some trick to this or any alternatives. I am stuck to Java 1.4 unfortunately.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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);
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...