Software Development

Parse Command-line Parameters with Apache Commons CLI

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).


The benefits of using this library is reduced development effort for and consistent usage format for both new and existing applications.


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.


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:

We would create an Option object like this:

Note that there’s this concept of short and long versions of options.


Parse parameters

We parse the parameters using CommandLineParser based on a set of Option objects stored in a container object using the Options class.

Inspect for values

If parsing the parameters did not throw a org.apache.commons.cli.ParseException, we proceed to inspecting for values of interest.



Using the codes we have so far, we invoke the program with two (2) options and get the following result.


Download the codes


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like