Java Reference
In-Depth Information
Finally, the file is closed.
r.close();
f.close();
The real work of loading the configuration file is done by the
loadLine
method,
which is discussed in the next section.
Reading a Line from the Configuration File
The
loadLine
method begins by checking for a colon (:) character. This character
separates a name from a value. If no colon is found, then the line is invalid, so it is simply
ignored.
String name, value;
int i = line.indexOf(':');
if (i == -1) {
return;
}
The
name
and
value
variables are extracted from each side of the colon.
name = line.substring(0, i).trim();
value = line.substring(i + 1).trim();
If the value has no length, then it is assumed to be
null
.
if (value.trim().length() == 0) {
value = null;
}
Next, reflection is used to look up the
name
variable. The names in the configuration file
must match the names of the properties in the
SpiderOptions
class. If the variable can
not be found, then an error will be thrown, which is caught by the
load
method.
Field field = this.getClass().getField(name);
If the variable is of type
String
, then we simply set the variable to the
value
vari-
able that was parsed earlier.
if (field.getType() == String.class) {
field.set(this, value);
}
If the variable is a
List
, then the value variable is simply added to the
List
.
if (field.getType() == List.class) {
List<String> list = (List<String>) field.get(this);
list.add(value);