Menu

Quick_Guide

Ray

Quick Guide

Well, you know you should read the whole documentation, but you need just a quick fix of your application to recognize command line options? Let's say your application processes a list of strings, but you need to add a verbose option and also allow your application to read the strings from a file. The option that switches to verbose could be -v and the file option could be -f filename.

First, download the CmdConfig.jar and add it to your CLASSPATH. This way you get the access to the cz.phalanx.config.Config class.

Second, import the class, the best placement is in the class file of your main class:

import cz.phalanx.config.Config;

Third, instantiate the Config class, specifying the options you want to be recognized. The best placement is at the start of your main() method:

public static void main(String...args)
{
    Config config = new Config("vf:");
    /* your code continues here */
}

The "vf:" is an option string, which tells the parser to expect a -v option with no argument (it's a boolean option) and a -f option that must have an argument.

Fourth, let the parser process the arguments your main() method got:

    boolean correct = config.parseArguments(args);

Check the correct value - if it is false, then your -f option was passed without an argument. In this case you can decide to abort the program, or just to issue a warning and process only the strings your application was given at the command line.

Fifth, check the presence of your options and their arguments:

    if (config.isOn('v'))
        System.out.println("Program is running in verbose mode.");

    if (config.isOn('f'))
        processInputFile(new FileInputStream(new File(config.getOptionArgs('f')[0])));

The getOptionArgs() method returns an array for defined options (passed to the constructor), null for undefined options. But you can be sure that when the parseArguments() returned true, your -f option had at least one argument (it could have more of them).

Sixth, process the strings given at the command line just as you did it before, but instead of processing the args array argument of main(), you pick up the remaining (non-option) arguments from config:

    processStrings(config.getArguments());

That's it. :-)


Related

Wiki: Overview