I am currently using the library Apache Commons CLI 1.3.1
to parse command line arguments and control the flow of execution in an executable jar. So far everything has been pretty straightforward and the documentation and example usage pages have been relatively thorough and helpful.
However, I am still unclear about how to use this library to detect the absence of any arguments or options. I would like to detect this condition and then print a usage/help statement. I have gotten around this by simply checking the length of the argument array, but I would like to know if the library has a way of detecting this condition without checking for the presence of every option.
Here is my code with the work-around left in:
public static void main(String[] args)
{
try
{
// create Options object
Options options = new Options();
// add t option
options.addOption("t", false, "display current time");
options.addOption("help", false, "print this message");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if(cmd.hasOption("t")) {
log.debug("Received option t");
// Do something
}
if (args.length <= 0 || cmd.hasOption("help"))
{
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "java -jar Client.jar <option> <arguments>", options);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
I think you're looking for the getArgList
or the getArgs
method. From the documentation:
Retrieve any left-over non-recognized options and arguments
So instead of this:
if (args.length <= 0 || cmd.hasOption("help"))
Use like this:
if (cmd.getArgs().length == 0 || cmd.hasOption("help"))