Skip to main content

How to Use Java Properties Classes

The JavaProperties class wraps a Dictionary<string, string> class to provide the following additional features:

  • Load Java properties from a Stream into the Dictionary<string, string>
  • Load Java properties from a Stream with an alternate (e.g. Unicode) encoding – easier to support languages in alternate character sets.
  • Store Java properties to a Stream from the Dictionary<string, string>.
  • Support default properties (as with Java Properties class) using the 2nd constructor which provides a Dictionary<string, string> 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 and sample applications 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:

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 Dictionary<string, string>.

Or, for a non-standard (e.g. Unicode) Encoding:

Store Properties

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

The file is created with a timestamp comment at the top followed by a second comment line with the provided comment string (if not null). 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 Dictionary<string, string> into a Stream.