Skip to main content

Loading a Settings File

Using a Settings.ini file to populate required properties.


Helper_Load_Properties.java

The following code sample illustrates how to use a settings file to set required properties.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class Helper_Load_Properties {

private Properties props;

public Helper_Load_Properties(String file, String args[], boolean verbose) {
this(file); // Go ahead and invoke the base constructor.

List<String> bad_args = new ArrayList<String>();
List<String> sad_args = new ArrayList<String>();

for (int curr_arg = 0; curr_arg < args.length; curr_arg++) {

String arg = "";
String val = "";

String[] parts = args[curr_arg].split("=");

if (parts.length == 2) {
arg = parts[0].trim();
val = parts[1].trim();

if (props.getProperty(arg) == null) {
sad_args.add(args[curr_arg]);
}

props.setProperty(arg, val);

}
else {
bad_args.add(args[curr_arg]);
}
}

if (verbose) {
if (bad_args.size() > 0) {
System.out.println("One or more arguments could not be correctly parsed. These will be ignored:");
for (int i = 0; i < bad_args.size(); i++) {
System.out.println("\t" + bad_args.get(i));
}
}

if (sad_args.size() > 0) {
System.out.println("One or more argument names does not match a pre-existing argument name in the configuration file. These will be applied anyway:");
for (int i = 0; i < sad_args.size(); i++) {
System.out.println("\t" + sad_args.get(i));
}
}

if ((bad_args.size() > 0) || (sad_args.size() > 0)) {
System.out.println("For arguments that contain spaces, surround the entire statement in quotes like, \"user=Eleanor Frisbee\". Argument names and values will have beginning and ending spaces trimmed away. Don't surround values in ' characters.");
}
}

}

public Helper_Load_Properties(String file) {
props = new Properties();
InputStream input = null;

try {
input = new FileInputStream(file);
props.load(input);
}
catch (IOException ex) {
System.out.println("The specified settings file, \"" + file + "\" could not be found.");
}
finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public void list() {
Set<Entry<Object, Object> > set = props.entrySet();
Iterator<Entry<Object, Object>> iter = set.iterator();

System.out.println("Settings Loaded:");
while (iter.hasNext()) {
Entry<Object, Object> ent = iter.next();
System.out.println("\t" + "arg: " + ent.getKey() + "\t" + "val: " + ent.getValue());
}

}

public String get(String prop) {
String retVal = props.getProperty(prop);

if (retVal == null) {
throw new NullPointerException("The key \"" + prop + "\" does not exist in the configuration file.");
}

return retVal;

}

}