在 Java 运行时设置 windows PATH 环境变量

我有一个使用 Runtime.exec() 方法触发可执行文件的 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.

我尝试设置的环境变量是路径,所以我传入PATH=C:somepath".这不起作用.是否有一些技巧或任何替代方法.不幸的是,我坚持使用 Java 1.4.

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.

推荐答案

使用getenv 获取环境并修复它,然后使用 exec 执行 exec.

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

}

相关文章