Discussion Locked

To read Environment Variables in java

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
How to read the environment variable that is set in the windows os, inside the java program?(Environment variables such as CATALINA_HOME,ANT_HOME etc..)

3 replies

by rashmigopinath

You can retrieve the Java-defined system properties in your code using the
System.getProperty()method.
You can use the following code to determine which are the Java-defined system
properties on your machine:
public static void main( String [] args ) {
java.util.Properties p = System.getProperties();
java.util.Enumeration keys = p.keys();
while( keys.hasMoreElements() ) {
System.out.println( keys.nextElement() );
}
}

If you have read the value of an environment value set on your Windows OS (for
example the value of path variable), then you would have to do the following:

public static void main(String[] args)
{
String path = System.getProperty("path");
System.out.println("the value of path is "+path);
}

While running the above code, you would have to run it as:
java -Dpath="%path%" myClassname

Thus, whatever environment variable that you want to read in your java file, you
would need to specify that in the java command while running the file.
eg:
java -Dpath="%path%" -Dclasspath="%classpath%" myClassname

Do let me know if you have any more questions.

Rgds,
Rashmi

This discussion is closed to new replies.