layout | toc_group | link_title | permalink |
---|---|---|---|
ni-docs |
how-to-guides |
Access Environment Variables |
/reference-manual/native-image/guides/access-environment-variables/ |
A native executable accesses your environment variables in the same way as a regular Java application. For example, assume you have the following source code:
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
var filter = args.length > 0 ? args[0] : "";
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
if(envName.contains(filter)) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
}
This code iterates over your environment variables and prints out the ones that contain the String of characters passed as the command-line argument.
-
Compile the file and build a native executable, as follows:
javac EnvMap.java native-image EnvMap
-
Run the resulting native executable and pass a command-line argument, such as "HELLO". There should be no output, because there is no environment variable with a matching name.
./envmap HELLO <no output>
-
Create a new environment variable named "HELLOWORLD" and give it the value "Hello World!". (If you are using a
bash
shell, follow the example below.) Now, run the native executable again--it will correctly print out the name and value of the matching environment variable(s).export HELLOWORLD='Hello World!' ./envmap HELLO
You should receive the expected output:
HELLOWORLD=Hello World!