Menu

Example

Ray

CmdConfig Example

The example code below shows a simple example that expects some options and prints what's been found at the command line. The options are expected as follows:
-a - a boolean option not accepting any argument values
-d - a boolean option, not accepting values
-b - an option with a mandatory argument value
-c - an option with an optional argument value

import cz.phalanx.config.Config;

public class Example
{
    public static void main(String ... args)
    {
        // construct the parser:
        Config config = new Config("ab:c::d");

        // parse the arguments
        if (!config.parseArguments(args))
            System.exit(1); // the error is already written
        else
        {
            // process the arguments. For a command line like:
            // example -abone -cb two -a three -c four five
            // yields this results:
            //config.isOn('a') == true;
            //config.isOn('b') == true;
            //config.isOn('c') == true;
            //config.isOn('d') == false;
            //config.getOptionArgs('b') is {"one", "two"}
            //config.getOptionArgs('c') is {"four"}
            //config.getArguments() is {"three", "five"}

            for (char opt: "abcd".toCharArray())
            {
                if (config.isOn(opt))
                {
                    System.out.println("Option `"+opt+"' is on.");
                    String[] optargs = config.getOptionArgs(opt);
                    if (optargs.length > 0)
                    {
                        System.out.print("Option `"+opt+"' has following values:");
                        for (String optval: optargs)
                            System.out.print(" "+optval);
                        System.out.println();
                    }
                 }
                 else
                   System.out.println("Option `"+opt+"' is off.");
            }
            System.out.print("Non-option arguments:");
            if (config.getArguments() != null)
            {
                for (String optval: config.getArguments())
                    System.out.print(" "+optval);
            }
            else
                System.out.print(" None.");
            System.out.println();
        }
    }  
}

Related

Wiki: Overview