Usage: How to Use JavaProperties Classes

The JavaProperties class wraps a Hashtable class to provide the following additional features:

  • Load Java properties from a Stream into the Hashtable.
  • Store Java properties to a Stream from the Hashtable.
  • Support default properties (as with Java Properties class) using the 2nd constructor which provides a Hashtable of defaults.
  • Coerce the property keys and values to strings (as they are for Java properties).

This page presents some basic examples of how the classes can be used. For more examples, refer to the Test classes which are also in the GitHub repository.

Load Properties

Properties may be loaded from any Stream - the following snippet of code shows how to read them from a file:


    String filename = "C:/PathToFile/myapp.properties";
    JavaProperties props = new JavaProperties();
    Stream stream = null;

    try
    {
        stream = new FileStream( filename, FileMode.Open );
        props.Load( stream );
    }
    catch( Exception ex )
    {
        // Handle the exception.
    }
    finally
    {
        if( stream != null )
        {
            stream.Close();
        }
    }

The Load method may throw all of the usual File IO exceptions as well as a ParseException if the syntax of the properties file is invalid.

The Load method uses an instance of the JavaPropertiesReader class to read properties from the Stream. This class can be used directly to load all the properties from a Stream into an instance of a Hashtable.


    Hashtable props = new Hashtable();
	JavaPropertyReader reader = new JavaPropertyReader( props );
	reader.Parse( streamIn );

Store Properties

Properties may be stored to any Stream - the following snippet of code shows how to store them in a file:


    String filename = "C:/PathToFile/myapp.properties";
    JavaProperties props = new JavaProperties();
    Stream stream = null;

    try
    {
        stream = new FileStream( filename, FileMode.Create );
        props.Store( stream, "A Comment String for the output file" );
    }
    catch( Exception ex )
    {
        // Handle the exception.
    }
    finally
    {
        if( stream != null )
        {
            stream.Close();
        }
    }

The file is created with a timestamp comment at the top followed by a second comment line with the provided comment string. Then, each of the properties are written as "name=value" pairs.

The Store method may throw all of the usual File IO exceptions.

The Store method uses an instance of the JavaPropertiesWriter class to store properties into the Stream. The following code shows how this class can be used to store all the properties from a Hashtable into a Stream.


    Hashtable props = new Hashtable();
    JavaPropertyWriter writer = new JavaPropertyWriter( props );
    writer.Write( streamOut, comments );