Jump to Real's How-to Main page

Retrieve environment variable (JNI)

For some odd reasons, the getenv() method was removed from the JDK. Rumors is that a mechanism to retrieve an environment will be back in JDK1.5 (see this HowTo). But for now, you can use -D switch to retrieve named environment variable and pass them to the JVM (see this HowTo) or use this JNI routine :
JNIEXPORT jstring JNICALL JavaHowTo_getenv
  (JNIEnv *env, jclass c, jstring jname){
    if ( jname == NULL ) { 
       return NULL ; 
    }
    const char *name =
       (*env)->GetStringUTFChars(env, jname, (jboolean *)NULL) ;
    const char *value = getenv(name) ;
    (*env)->ReleaseStringUTFChars(env, jname, name) ;
    return value ? (*env)->NewStringUTF(env, value) : NULL ;
}
NOTE : This is fine if the environment variable contains only regular 7-bit ASCII characters.

See also this HowTo.


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]