Friday Jun 24

System Properties in Java

PDF Print E-mail
Tuesday, 31 May 2011 06:15

Sometimes you need to display the list of System Properties defined in your application but you don't know where they are defined. Using the following snippet you can loop through the properties and display them using your favorite method.

Typically you get one property at a time by supplying the key in a call to System.getProperty().

  • String System.getProperty(String key)
    Returns the value of property key as a String.
  • String System.getProperty(String key, String default)
    Returns the value of property key as a string, or default if the property did not exist.
  • Properties System.getProperties()
    Returns a Properties object which has the value of all the properties. There are several ways to work with this object; see below for one example.

System properties

From System Properties you can find information about the operating system, the user, version of Java, etc... System class is a final class and cannot be instantiated , hence it provides us three static methods to retrieve system properties. The property names (keys) and values are stored in a Properties structure.A Properties object can also be used to store your own program properties in a file.

Iterate system properties using Enumeration

Spring java source

Properties props = System.getProperties();
Enumeration e = props.propertyNames();

while (e.hasMoreElements()) {
    String key = (String) e.nextElement();
    System.out.println(key + " = " + props.getProperty(key));
}

Iterate system properties using a for each loop

Spring java source

Properties props = System.getProperties();
for (String key : props .stringPropertyNames()) {
    System.out.println(key + " = " + props .getProperty(key));
}

Listing System properties alphabetically

Spring java source

Properties props = System.getProperties();
SortedMap sortedSystemProperties = new TreeMap(props);
Set keySet = sortedSystemProperties.keySet();
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
    String key = (String) iterator.next();
    System.out.println(key + " = " + props .getProperty(key));
}

Add comment


Security code
Refresh