Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set environment variables from code? [duplicate]

Tags:

java

I am trying to install apche tomcat. There arises a need to set environment variable's , how can I set environment variable?

I tried using ProcessBuilder but it doesn't work:

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();
}
like image 335
Mohammed Anwar Avatar asked Aug 15 '26 19:08

Mohammed Anwar


1 Answers

Example is here:

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);  
        }  
    }  
} 
like image 126
Zaheer Ahmed Avatar answered Aug 17 '26 09:08

Zaheer Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!