Java命令行解析:apache commons-cli

本文深入探讨了Apache CommonsCLI库的功能,包括解析命令行选项、输出选项说明信息及处理不同类型的选项(如POSIXlike、GNUlike、Java-like等)。详细介绍了定义选项、解析命令行参数、查询选项以及展示帮助信息的过程。

http://commons.apache.org/proper/commons-cli/usage.html

Apache Commons CLI用于解析命令行选项,也可以输出详细的选项说明信息。

Commons CLI 支持多种选项类型:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)

Commons CLI处理过程可以分成三个阶段

  • 定义阶段,Options类。
  • 解析阶段,使用CommandLineParser类讲String[] args解析为CommandLine
  • 查询阶段,调用CommandLine对象的方法,查询和提取特定选项。
命令行选型定义
Options options = new Options();
options.addOption("h", "help", false, "Print this usage information");  
options.addOption("v", "verbose", false, "Print out VERBOSE information" );  
options.addOption("p", false, "no error if existing, make parent directories as needed.");

options.addOption(OptionBuilder.withArgName("file")
                .hasArg()
                .withDescription("search for buildfile towards the root of the filesystem and use it")
                .create("O"));
options.addOption(OptionBuilder.withLongOpt("block-size")
                .withDescription("use SIZE-byte blocks")
                .withValueSeparator('=')
                .hasArg()
                .create() );
解析
CommandLineParser parser = new BasicParser( );  
CommandLineParser parser = new PosixParser(); 
CommandLine commandLine = parser.parse( options, args );  
选型查询和提取
  if( commandLine.hasOption('f') ) {  
    file = commandLine.getOptionValue('f');  
  }  

  String[] str = commandLine.getArgs();
显示帮助信息
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("xxcmd [-lkjs] PATH", "", options , "");
formatter.printHelp( "ant", options );
formatter.printHelp( "ant", options, true ); //generate a usage statment as well as the help information

转载于:https://www.cnblogs.com/pixy/p/5261347.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值