Tuesday 6 August 2013

Top Most How to get environment variables in Java- Example Tutorial

Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retriving Java Classpath or java.username  to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand Sytem.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. Sytem.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process while System.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and  How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.

How to get environment variables in Java - Example

How to get value of environment variable in Java - example tutorialHere is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory.

/**
 * Java program to demonstrate How to get value of environment variables in Java.
 * Don't confuse between System property and Environment variable and there is separate
 * way to get value of System property than environment variable in Java, as shown in this
 * example.
 *
 * @author Javin Paul
 */


public class EnvironmentVariableDemo {  

    public static void main(String args[]){
   
      //getting username using System.getProperty in Java
       String user = System.getProperty("user.name") ;
       System.out.println("Username using system property: "  + user);
   
     //getting username as environment variable in java, only works in windows
       String userWindows = System.getenv("USERNAME");
       System.out.println("Username using environment variable in windows : "  + userWindows);
   
     
     //name and value of all environment variable in Java  program
      Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));
        }

    }
     
}

Output:
Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:\Documents and Settings\harry
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_20\
TEMP=C:\DOCUME~1\harry\LOCALS~1\Temp


Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :

1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows  e.g. USERNAME and Unix as USER.

2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.

3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.

That's all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty()to get that value in a platform independent way, if that environment variable is available as system property in Java.

Other How to tutorials from Javarevisited Blog

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt