Click here to Skip to main content
Click here to Skip to main content

Argument Parser

, 27 Nov 2012
Rate this:
Please Sign up or sign in to vote.
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nagy Vilmos
President Belligerent Bad Tempered Old Fools Club
United Kingdom United Kingdom
Do not tell anyone I am not Hungarian. It's a huge secret.
I have worked across too many platforms over the years - COBOL, Pascal, C, C++, VB3-6, C# and java are some of them - and now I just write pretty front ends for users with less wit than a gumby.
 
If I had a pound for everything I've learned over the years, I'd have £12,879.73
 
Semper ebrius, quantum variat.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
Questionstatement is incorrect Pinmemberswong88827-Nov-12 15:18 
AnswerRe: statement is incorrect PinmemberNagy Vilmos27-Nov-12 22:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140902.1 | Last Updated 28 Nov 2012
Article Copyright 2012 by Nagy Vilmos
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid