Getting Environment Variables

Problem

You want to get at environment variables from within your Java program.

Solution

Don’t.

Discussion

The seventh edition of Unix, released in 1979, had an exciting new feature known as environment variables. Environment variables are in all modern Unix systems and in most later command-line systems such as the DOS subsystem underlying MS-Windows, but are not in Macintosh computers, Palm Pilots, SmartCards, or other Java environments. Environment variables are commonly used for customizing an individual computer user’s runtime environment, hence the name. To take one example that will be familiar to most readers, on Unix or DOS the environment variable PATH determines where the system will look for executable programs. So of course the issue comes up: “How do I get at environment variables from my Java program?”

The answer is that you can do this in some versions of Java, but you shouldn’t. Java is designed to be a portable runtime environment. As such, you should not depend on operating system features that don’t exist on every single Java platform. I just mentioned several Java platforms that don’t have environment variables.

Oh, all right, if you insist. There is a static method called getenv( ) in class java.lang.System . Let’s try it out. But remember, you made me do it. First, the code. All we need is this line in a main program:

System.out.println("System.getenv("PATH") = " + System.getenv("PATH"));

Let’s try compiling it:

C:javasrc>javac GetEnv.java
Note: GetEnv.java uses or overrides a deprecated API. Recompile with -deprecation 
for details.

That message is seldom welcome news. We’ll do as it says:

C:javasrc>javac -deprecation GetEnv.java
GetEnv.java:9: Note: The method java.lang.String getenv(java.lang.String) in class
 java.lang.System has been deprecated.
System.out.println("System.getenv("PATH") = " + System.getenv("PATH"));
                                                         ^
Note: GetEnv.java uses or overrides a deprecated API.  Please consult the 
documentation for a better alternative.
1 warning

But it’s only a warning, right? What the heck. Let’s try running the program!

C:javasrc>java  GetEnv
Exception in thread "main" java.lang.Error: getenv no longer supported, use 
properties and -D instead: PATH
        at java.lang.System.getenv(System.java:602)
        at GetEnv.main(GetEnv.java:9)

Well, of all the non-backwards-compatible things! It used to work, in JDK 1.1, but it really and truly doesn’t work anymore in Java 2. I guess we’ll just have to do what the error message tells us, which is to learn about “properties and -D instead.” In fact, that’s our very next recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.174.253