Using Apache common-cli to parse arguments

6.9k views Asked by At

Apache common-cli has a example on its web site for ls command:

options.addOption( "a", "all", false, "do not hide entries starting with ." );
options.addOption( "A", "almost-all", false, "do not list implied . and .." );
options.addOption( "b", "escape", false, "print octal escapes for nongraphic " + "characters" );
options.addOption( OptionBuilder.withLongOpt( "block-size" )
                                .withDescription( "use SIZE-byte blocks" )
                                .hasArg()
                                .withArgName("SIZE")
                                .create() );

This shows help like this:

-a, --all                  do not hide entries starting with .
-A, --almost-all           do not list implied . and ..
-b, --escape               print octal escapes for nongraphic characters
    --block-size=SIZE      use SIZE-byte blocks
  1. When I write this code, it shows --block-size <SIZE>. I want to show something like this: -z,--block-size=SIZE(not just long option).
  2. what is the difference of PosixParser and GnuParser? I changed them in the code, I didn't observed any difference.
  3. When I provide wrong option for example h it doesn't throw any ParseException. The program starts and finishes normally.
1

There are 1 answers

0
Emmanuel Bourg On BEST ANSWER
  1. The block size option in the example has only a long format, that's why there is no short option shown. If you add a short alias you'll get the result you expect

  2. PosixParser and GnuParser are deprecated in the latest version of Commons CLI. A new unified parser is available as DefaultParser. The posix parser had the ability to parse concatenated short options, something like tar -zxvf foo.tar.gz.

  3. Extra options are either handled as arguments to the application or trigger an exception, depending of the value of the stopAtNonOption parser parameter.