Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Application Security Testing: An Integral Part of DevOps

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("?") {
        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) :
                String value = (loc > 0) ? args[i].substring(loc+1) :
                options.put(key.toLowerCase(), value);
            else {

    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.



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