1. Create a configuration
A configuration file consists of a description
and an unlimited number of configuration sections.
To create a configuration file, an
XMLConfig
object needs to be defined. Following code snippet
shows how to create a new
XMLConfig object
with or without description:
XMLConfig xc = new XMLConfig(); // configuration with no description
|
or
XMLConfig xc = new XMLConfig("Description for the configuration file."); // with description
|
2. Define a configuration section
A configuration section has a description and an unlimited number
of configuration fields. Each configuration section will be
defined as a Java data class. The configuration fields of the
section can be defined as either public data members or pairs
of public get and set functions of the configuration section Java
data class.
A configuration field can be of most Java primitive data types.
The Java data types currently supported are:
- boolean/Boolean
- char/Character
- byte/Byte
- short/Short
- int/Integer
- long/Long
- float/Float
- double/Double
- String
Most of Java container data types are supported as well.
- array of primitive type elements
- List, Vector, ...
- Hashtable, HashMap, ...
The data elements in those container data types have to be
of the primitive Java data types listed above.
'SimpleConfigSection' listed below is a very simple configuration
section with 2 configuration fields:
import com.sunwesttek.util.config.ConfigSection;
public class SimpleConfigSection extends ConfigSection {
private String stringField;
// configuration field defined as a
// public data member
public short shortField;
// public default constructor
public SimpleConfigSection() {
setDescription("This is a simple config section.");
}
// configuration field defined as a pair
// of get/set functions
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
}
|
The Java data class defined for a configuration section must
meet following requirements:
- It has to be a 'public' class derived of 'ConfigSection'.
- If the default constructor is defined, it must be 'public'.
3. Add a configuration section to a configuration
Each section in the configuration needs to have a unique name.
Following code shows how to add a section to the configuration:
SimpleConfigSection scs = new SimpleConfigSection();
scs.shortField = (short)12345;
scs.setStringField("demo string");
xc.addSection("SimpleSectionName", scs);
|
4. Save configuration to a disk file
To save the configuration to a disk file, a user needs to call
one of the 'save' functions provided in
XMLConfig class:
xc.save(new File("foo.cfg"));
|