Tuesday, March 1, 2011

Parsing a Simple Command line containing optional and required arguments

I used Apache Commons CLI to parse the program arguments.
First,populate an Options object to configure command-line parsing.
Pass the Options class and a String[] of arguments to a CommandLineParser, which parses and returns a CommandLine object capturing the supplied options and parameters(arguments).

For the purposes of this , assume that am attempting to parse a command line with three optional arguments: -h, -v, and -f .
-h prints out a simple help message with usage information and available command-line options
-v runs the program with verbose logging
-f sends the output of the application to a file.
To parse this command line, our main( ) method would resemble the following code:


import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLine;
public class CommandLineSample {

public static void main(String[] args) throws Exception {
// Create a Parser
CommandLineParser parser = new BasicParser();
Options options = new Options( );
options.addOption("h", "help", false, "Print this usage information");
options.addOption("v", "verbose", false, "Print out VERBOSE information");
options.addOption("f", "file", true, "File to save program output to");
// Parse the program arguments
CommandLine commandLine = parser.parse( options, args );
// Set the appropriate variables based on supplied options
boolean verbose = false;
String file = "";
if( commandLine.hasOption('h') ) {
System.out.println( "Help Message");
System.exit(0);
}
if( commandLine.hasOption('v') ) {
verbose = true;
}
if( commandLine.hasOption('f') ) {
file = commandLine.getOptionValue('f');
}
}

}
The Options object tells the CommandLineParser to expect three arguments: -h, -v, and -f.
The first argument to options.addOption( ) is the short name or abbreviation of the option, and the second argument is the long name of the argument.
When the long name of an option is specified, either may be used as program arguments.
For example, a command line specifying short-name arguments, -h -v -f test.xml, is equivalent to a command line specifying long-name arguments, --help --version --file test.xml, and both short- and long-name arguments may be mixed in the same command line.
The third argument to options.addOption() specifies whether the option takes a parameter;
in the previous example, only the file option expects a parameter. The fourth parameter is a String containing a description of the option for a user.

No comments: