7.2. Parsing a Simple Command Line

Problem

You need to parse a simple command line containing optional and required arguments.

Solution

Use the Jakarta Commons CLI to parse program arguments. 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.

For the purposes of this recipe, assume that you are attempting to parse a command line with three optional arguments: -h, -v, and -f <filename>. -h prints out a simple help message with usage information and available command-line options, -v runs the program with verbose logging, and -f sends the output of the application to a file. To parse this command line, your 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 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 ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.