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
1 error


Anonymous said...

Wonder if that means that Java programmes can be used as CGI's on web servers

Factory Direct Party said...

@Anonymous: You'd never wanna use a Java app in a CGI environment. The startup times would make such apps verrrry slowe-starting. Second of all, why use CGI when you've got servlets and the tons and tons of brilliant technologies that have built-up around servlets all these years.

Anna said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Course in Chennai

Java Online Training India