Search This Blog

Wednesday 14 August 2013

Accesing System Properties in Java

In an earlier post we saw The ExceptionUtils class provided by the Commons Lang library. The library also provides us with a SystemUtils class - it provides us with information about the JVM in use and the underlying platform. Consider the below code:
public static void main(final String[] args) {
      System.out.println("java version is " + SystemUtils.JAVA_VERSION);
   }
The code prints the java version used for running the class.
java version is 1.6.0-rc
The same code could also be achieved without SystemUtils:
 System.out.println("java version is " + System.getProperty("java.version"));
In fact this is more or less the same code used by SystemUtils class. The class is simply a nice utility that makes things easy for us when it comes to such system related information.
There are several such properties. Some that I found interesting are:
public static void main(final String[] args) {
      System.out.println("file encoding is " + SystemUtils.FILE_ENCODING);
      System.out.println("java version is " + SystemUtils.FILE_SEPARATOR);
      System.out.println("class path is " + SystemUtils.JAVA_CLASS_PATH);
      System.out.println("class version is " + SystemUtils.JAVA_CLASS_VERSION);
      System.out.println("java endrosed dirs are " + SystemUtils.JAVA_ENDORSED_DIRS);
      System.out.println("java compiler is " + SystemUtils.JAVA_COMPILER);
      System.out.println("java home dir is " + SystemUtils.JAVA_HOME);
      System.out.println("java VM is " + SystemUtils.JAVA_VM_NAME);
   }
The output is :
file encoding is Cp1252
java version is \
class path is D:\Work\eclipse workspaces\Java ws
\ApacheCommons\bin;D:\Work\eclipse workspaces\Java ws\ApacheCommons\lib\commons-lang-2.2.jar
class version is 50.0
java endrosed dirs are C:\Program Files\Java\jre1.6.0\lib\endorsed
java compiler is null
java home dir is C:\Program Files\Java\jre1.6.0
java VM is Java HotSpot(TM) Client VM
The compiler property returned a null value. This is the case when the class was unable to read it. From the code comments:
Defaults to null if the runtime does not have security access to read this 
property or the property does not exist.
If we want to avoid the constants, there are methods available for fetching system information :
      System.out.println("java Home is " + SystemUtils.getJavaHome());
      System.out.println("user dir is " + SystemUtils.getUserDir());
If we need to know the underlying platform or Java version than also there are a host of constants available:
      System.out.println("Is Java version 6 " + SystemUtils.IS_JAVA_1_6 + " is it abov 1.4 "
            + SystemUtils.isJavaVersionAtLeast(14));
      System.out.println(" Is it windows NT ? " + SystemUtils.IS_OS_WINDOWS_NT + ", is it linux ? "
            + SystemUtils.IS_OS_LINUX);

No comments:

Post a Comment