System.getEnv
to
retrieve environment variable values. Without an argument,
getEnv
returns a read-only instance of
java.util.Map
, where the map keys are the environment
variable names, and the map values are the environment variable
values. This is demonstrated in the
EnvMap
example:
import java.util.Map; public class EnvMap { public static void main (String[] args) { Map<String, String> env = System.getenv(); for (String envName : env.keySet()) { System.out.format("%s=%s%n", envName, env.get(envName)); } } }
String
argument, getEnv
returns the
value of the specified variable. If the variable is not defined,
getEnv
returns null
. The
Env
example uses getEnv
this way to query specific environment
variables, specified on the command line:
public class Env { public static void main (String[] args) { for (String env: args) { String value = System.getenv(env); if (value != null) { System.out.format("%s=%s%n", env, value); } else { System.out.format("%s is not assigned.%n", env); } } } }
ProcessBuilder
object to create a new process, the default set of environment
variables passed to the new process is the same set provided to the
application's virtual machine process. The application can change this
set using ProcessBuilder.environment
.
USERNAME
, while UNIX implementations might provide the
user name in USER
, LOGNAME
, or both.
To maximize portability, never refer to an environment variable when
the same value is available in a system property. For example, if the
operating system provides a user name, it will always be available in
the system property user.name
.