在Java中运行时设置Windows PATH环境变量 [英] set windows PATH environment variable at runtime in Java
问题描述
我尝试设置的环境变量是路径,所以我传递PATH = C:\some\path。这不行。这个或其他任何方法有一些技巧吗?不幸的是我被困在Java 1.4上。
使用 http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System .html#getenv%28java.lang.String%29 获取环境并修复它,然后使用[ http ://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec%28java.lang.String,%20java.lang.String [],%20java.io.File %29] [1] 执行执行。
这个工作与批处理文件中有路径。
package p;
import java.util。*;
public class运行{
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 ++;
}
返回字符串;
}
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);
}
}
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.
use http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#getenv%28java.lang.String%29 to get the environment and fix it up then use a flavour of [http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec%28java.lang.String,%20java.lang.String[],%20java.io.File%29][1] 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环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!