How to add environment variable in Java?

Possible duplicate:
How to set environment variables from Java?

I am working on Java. I have to add an environment variable to the Java code so that it is available when I get the list using the 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 the above test, I cannot correctly get the environment variable. therefore How to set an environment variable?

+7
source share
4 answers
  Map<String, String> env = pb.environment(); env.put("MV_ENV_VAR", "1"); 

set MY_ENV_VAR = 1. Before you invoke the process

 Process p = pb.start(); 

export interpreted only by the shell.

See also ProcessBuilder

Full example:

 public static void main(String[] args) throws IOException { ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "SET"); Map<String, String> env = pb.environment(); env.put("MYVAR", "myValue"); Process p = pb.start(); InputStreamReader isr = new InputStreamReader(p.getInputStream()); char[] buf = new char[1024]; while (!isr.ready()) { ; } while (isr.read(buf) != -1) { System.out.println(buf); } } 

prints among other environment values:

 MYVAR=myValue 

This should prove that the created process uses a managed environment.

+6
source

You can get the environment variable using the Builder process object:

  ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2"); Map<String, String> env = pb.environment(); env.put("VAR1", "myValue"); env.remove("OTHERVAR"); env.put("VAR2", env.get("VAR1") + "suffix"); 
+3
source

You can add the necessary variables directly to the 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)); } } 

}

+2
source

From how-do-i-set-environment-variables-from-java

A possible way to alleviate the burden would be to eliminate the method

 void setUpEnvironment(ProcessBuilder builder) { Map<String, String> env = builder.environment(); // blah blah } 

and run ProcessBuilders through it before starting them.

In addition, you probably already know this, but you can start more than one process with the same ProcessBuilder . Therefore, if your subprocesses are the same, you do not need to do this setting again and again.

+1
source

All Articles