Environment Variables in Fortress

Our first look at environment variables will demonstrate how to set, get, and list these configuration parameters in Java.

import java.util.Map;

public class EnvironmentVariables {
    public static void main(String[] args) {
        // To set a key/value pair, use System.setProperty
        // To get a value for a key, use System.getenv
        // System.getenv will return null if the key isn't present in the environment
        System.setProperty("FOO", "1");
        System.out.println("FOO: " + System.getenv("FOO"));
        System.out.println("BAR: " + System.getenv("BAR"));

        // Use System.getenv() to get all environment variables
        // This returns a Map<String, String> of all key/value pairs
        System.out.println();
        Map<String, String> env = System.getenv();
        for (String key : env.keySet()) {
            System.out.println(key);
        }
    }
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is null.

$ java EnvironmentVariables
FOO: null
BAR: null

The list of keys in the environment will depend on your particular machine.

PATH
JAVA_HOME
USER
...

If we set BAR in the environment first, the running program picks that value up.

$ export BAR=2
$ java EnvironmentVariables
FOO: null
BAR: 2
...

Note that in Java, System.setProperty() sets a system property, not an environment variable. Environment variables are typically set outside of the Java program and cannot be modified at runtime. The System.getenv() method retrieves the environment variables.