The following sections describe some example scenarios on how to use CLI in applications.
A boolean option is represented on a command line by the presence of the option, i.e. if the option is found then the option value is true, otherwise the value is false.
The DateApp utility prints the current date to standard output. If the
-t option is present the current time is also printed.
An
Options object must be created and the t
Option must be added to it.
The addOption method has three parameters. The first
parameter is a char that represents the option. The
second paramter is a boolean that specifies whether the
option requires an argument or not. In the case of a boolean option
(sometimes referred to as a flag) an argument value is not present so
it false is passed. The third parameter is the description
of the option. This description will be used in the usage text of the
application.
The parse methods of Options are used to
parse the command line arguments.
Now we need to check if the t option is present. To do
this we will interrogate the
CommandLine
object. The hasOption method takes a
char parameter and returns true if the option represented
by the char is present, otherwise it returns false.
The InternationalDateApp utility extends the
DateApp utility by providing the ability to print the
date and time in any country in the world. To facilitate this a new
command line option, c, has been introduced.
The second parameter is true this time. This specifies that the
c option requires an argument value. If the required option
argument value is specified on the command line it is returned,
otherwise null is returned.
The getOptionValue methods of Options are
used to retrieve the argument values of options.