Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
May 28, 1999

Simplify Command-Line Argument Parsing

ArgumentParser simplifies command-line argument processing by separating arguments into positional parameters and options (any argument starting with "-" or "/" is considered an option, which may specify a value). Construct an ArgumentParser instance with your command-line arguments, then ask the ArgumentParser for parameters and options:
 
java YourClass -level=5 firstParam -verbose secondParam

in YourClass.java:
    public static void main(String[] args) {
        ArgumentParser p = new ArgumentParser(args);
        if (p.hasOption("?") {
            printUsage();
        }
        else {
            boolean verboseMode = p.hasOption("verbose");
            level = p.getOption("level");
            doSomethingWithParams(p.nextParam(), p.nextParam());
        }
    }

==================== ArgumentParser.java ====================
import java.util.*;
public class ArgumentParser {
    public ArgumentParser(String[] args) {
        for (int i = 0; i < args.length; i++) {
            if (args[i].startsWith("-") || args[i].startsWith("/")) {
                int loc = args[i].indexOf("=");
                String key = (loc > 0) ? args[i].substring(1, loc) :
args[i].substring(1);
                String value = (loc > 0) ? args[i].substring(loc+1) :
"";
                options.put(key.toLowerCase(), value);
            }
            else {
                params.addElement(args[i]);
            }
        }
    }

    public boolean hasOption(String opt) {
        return options.containsKey(opt.toLowerCase());
    }

    public String getOption(String opt) {
        return (String) options.get(opt.toLowerCase());
    }

    public String nextParam() {
        if (paramIndex < params.size()) {
            return (String) params.elementAt(paramIndex++);
        }
        return null;
    }
    private Vector params = new Vector();
    private Hashtable options = new Hashtable();
    private int paramIndex = 0;
}

Whit Stockwell
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date