使用Apache common-cli解析参数 [英] Using Apache common-cli to parse arguments
问题描述
Apache common-cli在其网站上有一个ls
命令的示例:
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() );
这显示了这样的帮助:
-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
- 编写此代码时,它显示
--block-size <SIZE>
.我想显示这样的内容:-z,--block-size=SIZE
(不只是 长选项). -
PosixParser
和GnuParser
有什么区别?我变了 他们在代码中,我没有发现任何区别. - 例如,当我提供错误的选项
h
时,它不会throw
任何ParseException
.该程序将正常启动和结束.
- 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). - what is the difference of
PosixParser
andGnuParser
? I changed them in the code, I didn't observed any difference. - When I provide wrong option for example
h
it doesn'tthrow
anyParseException
. The program starts and finishes normally.
推荐答案
-
示例中的块大小选项只有长格式,这就是为什么没有显示短选项的原因.如果添加简短的别名,您将获得预期的结果
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
PosixParser
和GnuParser
.一个新的统一解析器作为DefaultParser
可用. posix解析器能够解析串联的短选项,例如tar -zxvf foo.tar.gz
.
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
.
其他选项要么作为应用程序的参数处理,要么触发异常,具体取决于stopAtNonOption
解析器参数的值.
Extra options are either handled as arguments to the application or trigger an exception, depending of the value of the stopAtNonOption
parser parameter.
这篇关于使用Apache common-cli解析参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!