I want to set run configuration option : Environment variable while running JAR and run it using java code. How to set environment option while running jar through java code?
Asked
Active
Viewed 1.1k times
3
-
1Clarified title. – belwood May 15 '19 at 21:33
2 Answers
9
ENV_VAR=some-value java -jar path/to/theJar.jar
You can then access that in Java via System.getEnv('ENV_VAR')
In java you can also do system properties
java -Dsome.system.prop=some-value -jar path/to/theJar.jar
you can then access the system props in code via System.getProperty('some.system.prop')
fieldju
- 1,383
- 1
- 12
- 20
0
You simply need to pass your new variables to the exec method of Runtime, check this: https://stackoverflow.com/a/8607281/5032541
This is from the oracle doc : https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String,%20java.lang.String[])
To get the runtime, simply do Runtime.getRuntime()
There is an example:
List<String> env = new LinkedList<>();
System.getenv().forEach((key, value) -> env.add(key+"="+value));
env.add("MY_SUPER_NEW_ENV_VAR=AND_MY_SUPER_VALUE");
Runtime runtime = Runtime.getRuntime();
runtime.exec("/bin/bash", env.toArray(new String[0]));
Erwan Daniel
- 1,074
- 9
- 22