THE SIMPLE APPROACH
Commons-cli will provide you with everything you need to create simple or complex command line argument options, and then easily parse them. Options are configured in a few different ways.
The above snipit shows options being created using both the addOption method — by passing the various arguments — and using the OptionBuilder class to construct the options. The options are created with the following properties/attributes:
- opt – long & short versions, no argument, and a description
- help – long & short versions, no argument, and a description
- D – short version only, Java style properties (key=value), using = as the separator, with a description
- file – long version only, with argument, and description
Parsing a command line with these options is extremely simple: create a parser object and call the parse method on the String passed to the main method of the program. The SOP for parsers is the GnuParser, it will provide all of the features you’d expect.
The next step is checking for the arguments. This is done by simply calling the hasOption method on the CommandLine object returned from the parse call. If the option provides an argument, then you can get the value of the argument and check to see if it is null or not.
That is it! You now have 95% of all command line parsing you’ll ever need covered with this simple library and a few lines of code. There are more complex things you can do with commons-cli and you can see examples in the full source. If you have questions please ask in the comments. If you have bug fixes or improvements, please fork and make a pull request.
Thanks for reading…