• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access the evironment variable

 
Hussein Baghdadi
clojure forum advocate
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hola.
how can I access the environment variable of the OS inside my application ?
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.lang.System.getProperty
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To expand on what Tom said:

Officially, you can't get the environment variables. The Javasoft folks have tried to avoid including things in Java that don't exist on all the platforms Java might be implemented on. There is a method getenv() in the java.lang.System class, but if you call it nowadays, it just throws an exception:


getenv no longer supported, use properties and -D instead.


So what you're supposed to do is use the -D switch to the Java runtime to pass "properties" in which are set to the values of the environment variables of interest; i.e., on Windows, something like:

 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I could only answer for java 1.4 (haven't had a look at 1.5 yet).
There's no direct support for obtaining any environment variables. Java system properties are not identical to environment vars. There are some work arounds, non of them are 100 percent portable:

(1) Simplest and most recommended for simple cases: the batch invoking java will extract the environment variable & pass it as a java system property. For instance, passing windows environment variable PATH:


2) Write a c/c++ code that obtained the required environment var, then call it from java using JNI.

3) You could use class Runtime to invoke the operating system's ECHO command. It should be something like Runtime.getRuntime().exec("echo %path%") , but there's some extra work required for reading the output, and I don't remember the details.

4) As previous replies indicated, *some* environment variables (not all) may be automatically supplied by java as a system property. For instance, System.getProperty("java.class.path") will provide the classpath (however, note this is not exactly the same as accessing the CLASSPATH environment variable, since classpath may be determined by "java -classpath...."

Cheers
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic