Java命令行解析:apache commons-cli

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 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.");

                .withDescription("search for buildfile towards the root of the filesystem and use it")
                .withDescription("use SIZE-byte blocks")
                .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
posted @ 2016-03-11 14:13  XRacoon  阅读(2428)  评论(0编辑  收藏  举报