Introduction
Simply put, I often need to parse the arguments for a Java app and I always use a name value pair. After the 7th time of writing the same thing inside main
, I moved it out into a simple method.
Using the code
The arguments are passed into the method and out comes a Map
at the other side.
static public Map<String, String> parseArguments(String[] args) {
Map<String, String> argMap = new HashMap<String, String>();
String key = null;
int a = 1;
while (a < args.length) {
if (key==null) {
if (args[a].startsWith("-")) {
key = args[a].substring(1).toLowerCase();
if (argMap.containsKey(key)) {
throw new IllegalArgumentException
("Duplicate argument");
}
} else {
throw new IllegalArgumentException
("Argument names must begin with -");
}
} else {
argMap.put(key, args[a]);
key = null;
}
a++;
}
if (key != null) {
throw new IllegalArgumentException
("Argument without value");
}
return argMap;
}
That is really it. I use it like this:
public static void main(String[] args) {
Map<string,> options = ArgumentList.parseArguments(args);
String config = options.remove("config");
if (config == null) {
throw new IllegalArgumentException("No configuration supplied, use -config option");
}
String loggingOptions = options.remove("log");
if (!options.isEmpty()) {
throw new IllegalArgumentException("Invalid option in argument list.");
}
}
Removing each item and checking nothing is left at the end.