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 voidmain(String[] args)throwsException { // Create a Parser CommandLineParser parser =newBasicParser( ); Options options =newOptions( ); 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access