The Apache Common CLI library provides an API for parsing command line parameters passed to command-line programs in various familiar option-value formats, e.g., POSIX format (i.e., tar -zxvf myfile.tar.gz).
[wp_ad_camp_5]
The benefits of using this library is reduced development effort for and consistent usage format for both new and existing applications.
Requirements
Apache Commons CLI 1.x
This post uses the version 1.x or simply CLI. There is a CLI2 but it is still in the Commons Sandbox as of this writing.
Maven Dependency
The Java project for this post uses Maven and has this dependency for CLI.
[wp_ad_camp_4]
1 2 3 4 5 | <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.4</version> </dependency> |
Getting Started
We do 3 things with this API– define the option-value parameters’ format, parse parameters, and check the values passed to the program.
Define the option-value parameters’ format
In the CLI documentation, this is referred to as the Definition Stage. We use the Option
class to define the format of each option-value parameter. For example, we want something like:
1 | myapp --source=c:/some-dir/data.txt --delete-source-on-exit |
We would create an Option
object like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Options options = new Options(); Option sourceOption = Option.builder("s") .required(true) .hasArg(true) .longOpt("source") .desc("Full path to the source file") .build(); Option deleteSourceOnExit = Option.builder("dsoe") .required(false) .longOpt("delete-source-on-exit") .desc("Option to delete source file on program exit") .build(); options.addOption(sourceOption); options.addOption(deleteSourceOnExit); |
Note that there’s this concept of short and long versions of options.
[wp_ad_camp_3]
Parse parameters
We parse the parameters using CommandLineParser
based on a set of Option
objects stored in a container object using the Options
class.
1 2 | CommandLineParser cliParser = new DefaultParser(); CommandLine cmdLine = cliParser.parse(options, args); |
Inspect for values
If parsing the parameters did not throw a org.apache.commons.cli.ParseException
, we proceed to inspecting for values of interest.
1 2 | System.out.println("Source: " + cmdLine.getOptionValue("s")); System.out.println("Delete source on exit: " + cmdLine.hasOption("dsoe")); |
Testing
[wp_ad_camp_2]
Using the codes we have so far, we invoke the program with two (2) options and get the following result.
References
Download the codes
https://github.com/Turreta/Parse-Command-line-Parameters-with-Apache-Commons-CLI
[wp_ad_camp_1]