Wednesday, 15 June 2011

Using Environment Variables

Java SE 5 re-introduced the idea of allowing Java programs to get at a system's environment variables (I seem to remember that you could do this in the old days and that is was removed for 'non-portability' reasons).

Environment variables are accessed using the System.getEnv() method, which comes in two flavours:

  • Flavour 1: iterate around a map of all environment variables.
  • Falvour 2: get a particular variable

    // Flavour 1: iterate around a map of all environment variables.
   
Map<String, String> env = System.getenv();

   
for (Map.Entry<String, String> entry : env.entrySet()) {
     
System.out.println("Key: " + entry.getKey() + " value: " + entry.getValue());
   
}

    // Falvour 2: get a particular variable
   
System.out.println("\n\nJ2EE_HOME is: " + System.getenv("J2EE_HOME"));
    System.out.println
("\n\nPATH is: " + System.getenv("PATH"));

No comments: