Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an environment variable in Java? [duplicate]

Tags:

java

Possible Duplicate:
How do I set environment variables from Java?

I'm working on Java. I have to add an environment variable in java code programmatic such that it will be available when i get list using process builder as follows:

import java.util.Map;
import java.util.Set;

class helloworld  {
    public static void main(String[] args) {

        ProcessBuilder pb = new ProcessBuilder("export MY_ENV_VAR=1");

        Map<String, String> envMap = pb.environment();

        Set<String> keys = envMap.keySet();
        for(String key:keys){
            System.out.println(key+" ==> "+envMap.get(key));
        }

    }
}

But with above trial i cant get environment variable properly. so How to set the environment variable ?

like image 952
BSalunke Avatar asked Jan 18 '13 12:01

BSalunke


1 Answers

You can add the desired variables directly into ProcessBuilder.environment() map. The code below should work:

import java.util.Map;
import java.util.Set;

class helloworld  {
public static void main(String[] args) {

    ProcessBuilder pb = new ProcessBuilder("/bin/sh"); // or any other program you want to run

    Map<String, String> envMap = pb.environment();

    envMap.put("MY_ENV_VAR", "1");
    Set<String> keys = envMap.keySet();
    for(String key:keys){
        System.out.println(key+" ==> "+envMap.get(key));
    }

}

}

like image 69
maksim_khokhlov Avatar answered Oct 07 '22 00:10

maksim_khokhlov