set windows PATH environment variable at runtime in Java(在 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);
}
}
这篇关于在 Java 运行时设置 windows PATH 环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 运行时设置 windows PATH 环境变量
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
