我可以从代码中设置环境变量吗?

时间:2013-07-11 09:15:55

标签: java

我正在尝试安装apache tomcat。需要设置环境变量,如何设置环境变量?

我尝试使用ProcessBuilder,但它不起作用:

ProcessBuilder pb = new ProcessBuilder("CMD.exe", "/C", "SET"); // SET prints out the environment variables  
pb.redirectErrorStream(true);  
Map<String,String> env = pb.environment();  
String path = env.get("CATALINA_HOME") + apachePath;
env.put("CATALINA_HOME", path);  
Process process = null;
try {
    process = pb.start();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:2)

示例在这里:

import java.io.*;  
import java.util.*;  

public class Test  
{  
    public static void main(String[] args) throws Exception  
    {  
        ProcessBuilder pb = new ProcessBuilder("CMD.exe", "/C", "SET"); // SET prints out the environment variables  
        pb.redirectErrorStream(true);  
        Map<String,String> env = pb.environment();  
        String path = env.get("Path") + ";C:\\naved\\bin";  
        env.put("Path", path);  
        Process process = pb.start();  
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));  
        String line;  
        while ((line = in.readLine()) != null)  
        {  
            System.out.println(line);  
        }  
    }  
}