在Java中运行时设置Windows PATH环境变量 [英] set windows PATH environment variable at runtime in Java

查看:147
本文介绍了在Java中运行时设置Windows PATH环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆