Accessing Linux Environment Variable from Java Program

5.4k views Asked by At

I have Java Program which access the Linux Variable(example $VARD, i have exported the variable as well), I am accessing the variable value using Runtime.getRuntime("echo $VARD") function. Issue is it prints variable name instead of its value.

Note: I am running this program in Linux server where it has JAVA JDK 1.4 version. I knew we can do that using getenv().get() function which is available from JDK 1.5..

1

There are 1 answers

1
Marcin Szymczak On

In general you should use System.getProperty() or System.getEnv().

import java.lang.*;

public class SystemDemo {

   public static void main(String[] args) {

     // prints Java Runtime Version before property set
     System.out.print("Previous : ");
     System.out.println(System.getProperty("java.runtime.version" ));
     System.setProperty("java.runtime.version", "Java Runtime 1.6.0");

     // prints Java Runtime Version after property set
     System.out.print("New : ");
     System.out.println(System.getProperty("java.runtime.version" ));
   }
}

import java.util.Map;

public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",
                              envName,
                              env.get(envName));
        }
    }
}

If you are using maven there is another option. You can access environment variables from maven by using ${env.VARIABLE_NAME}.