Another Way to Access Environment Variables from Java Applications

How to pass environment variables to java applications? The traditional way is to pass them as system properties when starting the JVM (e.g., java -DCVSROOT=$CVSROOT ...), and then your java class can access it via System.getProperty("CVSROOT")

Starting from JDK 1.5, os environment variables can be directly accessed from within java. 2 new methods in java.lang.System are introduced for this purpose. Actually, getenv() first appeared in JDK 1, was then deprecated, and reinstated in JDK 5 (See this blog entry).
Before you go ahead testing them in your Foo.java, remember the method name is getenv, not getEnv.

I made the mistake when testing them:
C:\tmp > javac A.java
A.java:4: cannot find symbol
symbol : method getEnv(java.lang.String)
location: class java.lang.System
System.out.println(System.getEnv("CVSROOT"));
^
1 error

Followers

Pageviews Last 7 Days