Java Reference
In-Depth Information
most later command-line systems, such as the “DOS” or Command Prompt in Windows, but
are not in some older platforms or other Java runtimes. Environment variables are commonly
used for customizing an individual computer user's runtime environment, hence the name.
To take one familiar example, on Unix or DOS the environment variable PATH determines
where the system looks for executable programs. So of course the question comes up: “How
do I get at environment variables from my Java program?”
The answer is that you can do this in all modern versions of Java, but you should exercise
caution in depending on being able to specify environment variables because some rare oper-
ating systems may not provide them. That said, it's unlikely you'll run into such a system be-
cause all “standard” desktop systems provide them at present.
In some very ancient versions of Java, System.getenv() was deprecated and/or just didn't
work. Nowadays the getenv() method is no longer deprecated, though it still carries the
warning that System Properties (see Getting Information from System Properties ) should be
used instead. Even among systems that support them, environment variable names are case
sensitive on some platforms and case insensitive on others. The code in Example 2-1 is a
short program that uses the getenv() method.
Example 2-1. environ/GetEnv.java
public
public class
class GetEnv
GetEnv {
public
public static
void main ( String [] argv ) {
System . out . println ( "System.getenv(\"PATH\") = " + System . getenv ( "PATH" ));
static void
}
}
Running this code will produce output similar to the following:
C:\javasrc> java environ.GetEnv
System.getenv("PATH") = C:\windows\bin;c:\jdk1.8\bin;c:\documents
and settings\ian\bin
C:\javasrc>
The no-argument form of the method System.getenv() returns all the environment vari-
ables, in the form of an immutable String Map . You can iterate through this map and access
all the user's settings or retrieve multiple environment settings.
Both forms of getenv() require you to have permissions to access the environment, so they
typically do not work in restricted environments such as applets.
Search WWH ::




Custom Search