Printing the Java Environment/Properties

There are times when I have been programming in Java when I want to know about the system environment or system properties. I created the following class to print out the default properties and environment, but you could convert it to a utility class for use in a larger project.

For both environment variables and system properties I sort the results to make specific values easier to find.

import java.util.*;

public class EnvPrint
{
    public static void main(String args[])
    {

The first step is to get the system environment and print a header.

        Map<String,String> env = System.getenv();
        Iterator<String> keys = env.keySet().iterator();

        System.out.println();
        System.out.println("===== System Environment =====");
        System.out.println();

        ArrayList<String> list = new ArrayList<String>();

I make a sorted list to make reading easier.

        while(keys.hasNext())
        {
            String key = keys.next();
            list.add(key);
        }

        Collections.sort(list);

Then print the names and values.

        for(int i=0,max=list.size();i<max;i++)
        {
            String key = list.get(i);
            String value = env.get(key);
            System.out.println(key+" = "+value);
        }

Next I get the system properties and print them. Since one system property is the line separator, i escape occurrences of \n, \r and \f.

        Properties props = System.getProperties();
        Iterator propNames = props.keySet().iterator();

        System.out.println();
        System.out.println("===== System Properties =====");
        System.out.println();

        list.clear();

        while(propNames.hasNext())
        {
            String key = (String) propNames.next();
            list.add(key);
        }

        Collections.sort(list);

        for(int i=0,max=list.size();i<max;i++)
        {
            String key = (String)list.get(i);
            String value = String.valueOf(props.getProperty(key));
            value = value.replace("\n","\\n");
            value = value.replace("\r","\\r");
            value = value.replace("\f","\\f");
            System.out.println(key+" = "+value);
        }

And that is all there is to it.

    }
}
java