65.9K
CodeProject is changing. Read more.
Home

Argument Parser

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 22, 2012

CPOL
viewsIcon

13839

A simple method to parse an argument list as a name value pair

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. 

/**
 * Parse a string array of arguments into a map.
 * Takes an array of arguments and splits them into a map of name/value pairs.
 * Each argument name must be unique and prefixed by - and have a single value.
 * Example:
 * -debug TRUE -name "William Norman-Walker" -number 7
 * @param args  An array of arguments containing name/value pairs.
 * @return      The arguments as a map.
 * @throws IllegalArgumentException
 *              thrown when the arguments are in an incorrect format.
 */
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.");
    }
    // code goes here...
}

Removing each item and checking nothing is left at the end.