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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.