Commons CLI使用详解


Preface:

Apache Commons CLI library为用户提供了一个解释命令行的API.它在解释命令行时主要有三个状态,即:定义、解释和询问交互。下面的部分中将会详细的讨论这三个部分的内容,以及怎么样利用CLI实现它们。

接下来的部分就是一些实例,通过实例演示了如何使用Commons CLI来解释处理命令。

Example:

下面就是我们要实现的效果(在这里参数与命令没有任何特殊意义,只是为了表示如何完成相应的功能):

  1. usage: gmkdir [-p][-v/--verbose][--block-size][-h/--help] DirectoryName
  2.  --block-size    use SIZE-byte blocks
  3.  -O <file>         search for buildfile towards the root of the filesystem and use it
  4.  -p                    no error if existing, make parent directories as needed.
  5.  -v,--verbose    explain what is being done.
  6.  -h,--help          print help for the command.

参数说明与使用场景:

--block-size: use SIZE-byte blocks,在命令参数中使用场景为:gmkdir --block-size=10 testmkdir

-O <file>          search for buildfile towards the root of the filesystem and use it,在命令中使用场景为:gmkdir  -O test.txt testmkdir

-p                    no error if existing, make parent directories as needed.,在命令中使用场景为:gmkdir  -p testmkdir

-v,--verbose    explain what is being done.,在命令中使用场景为:gmkdir  -v testmkdir或gmkdir  --verbose testmkdir

 -h,--help          print help for the command.,在命令中使用场景为:gmkdir  -h

综合使用场景为:

gmkdir  -h --可以查看该命令的帮助信息;

gmkdir  -v testmkdir 或 gmkdir testmkdir  -v

gmkdir  -v -p testmkdir/test1/test2/test3 或 gmkdir testmkdir/test1/test2/test3 -v -p

gmkdir  -O test.txt testmkdir -v  或 gmkdir testmkdir  -O test.txt -v 

gmkdir --block-size=10 testmkdir -v 或 gmkdir testmkdir -v --block-size=10

gmkdir --block-size=10 testmkdir/test1/test2/test3 -p

... ...

大家通过以上场景可以看到命令的参数的位置可以放置于命令后的任何位置,CLI将会帮助我们完成相应的解释工作,需要注意的是类似与-O <file>和--block-size,其后面的参数必须得紧跟其后,如-O test.txt 、--block-size=10 ... 

以上混乱的说明了要实现如上述的命令效果和场景,接下来就对具体的实现进行详细的说明。代码如下,具体实现通过注释表示:

  1. package org.system.faye.commandline;
  2. import org.apache.commons.cli.CommandLine;
  3. import org.apache.commons.cli.CommandLineParser;
  4. import org.apache.commons.cli.HelpFormatter;
  5. import org.apache.commons.cli.OptionBuilder;
  6. import org.apache.commons.cli.Options;
  7. import org.apache.commons.cli.ParseException;
  8. import org.apache.commons.cli.PosixParser;
  9. public class Mkdir {
  10.     /**
  11.      * @param args
  12.      */
  13.     public static void main(String[] args) {
  14.         Options opt = new Options();
  15.         opt.addOption("p"false"no error if existing, " +
  16.                 "make parent directories as needed.");
  17.         opt.addOption("v""verbose"false"explain what is being done.");
  18.         opt.addOption(OptionBuilder.withArgName("file")
  19.                 .hasArg()
  20.                 .withDescription("search for buildfile towards the root of the filesystem and use it")
  21.                 .create("O"));
  22.         opt.addOption(OptionBuilder.withLongOpt("block-size")
  23.                 .withDescription("use SIZE-byte blocks")
  24.                 .withValueSeparator('=')
  25.                 .hasArg()
  26.                 .create() );
  27.         opt.addOption("h""help"false"print help for the command.");
  28.        
  29.         String formatstr = "gmkdir [-p][-v/--verbose][--block-size][-h/--help] DirectoryName";
  30.        
  31.         HelpFormatter formatter = new HelpFormatter();
  32.         CommandLineParser parser = new PosixParser();
  33.         CommandLine cl = null;
  34.         try {
  35.             // 处理Options和参数
  36.             cl = parser.parse( opt, args );
  37.         } catch (ParseException e) {
  38.             formatter.printHelp( formatstr, opt ); // 如果发生异常,则打印出帮助信息
  39.         }
  40.         // 如果包含有-h或--help,则打印出帮助信息
  41.         if (cl.hasOption("h")) {
  42.             HelpFormatter hf = new HelpFormatter();
  43.             hf.printHelp(formatstr, "", opt, "");
  44.             return;
  45.         }
  46.         // 判断是否有-p参数
  47.         if (cl.hasOption("p")) {
  48.             System.out.println("has p");
  49.         }
  50.          // 判断是否有-v或--verbose参数
  51.         if (cl.hasOption("v")) {
  52.             System.out.println("has v");
  53.         }
  54.         // 获取参数值,这里主要是DirectoryName
  55.         String[] str = cl.getArgs();
  56.         int length = str.length;
  57.         System.out.println("length="+length);
  58.         System.out.println("Str[0]="+str[0]);
  59.         //判断是否含有block-size参数
  60.         if( cl.hasOption( "block-size" ) ) {
  61.             // print the value of block-size
  62.             System.out.println("block-size=" + cl.getOptionValue("block-size"));
  63.         }
  64.     }
  65. }

由于时间关系,这里对Option、Options与CommandLineParser 暂时不作说明,稍后会加上,如果大家存在任何疑问,可以随时联系我,我会在第一时间恢复大家。 

大概的了解了CLI,现在马上运行看一下呢?(*^__^*) 嘻嘻……是不是很酷啊?哈哈!~

本文永久更新链接地址

相关内容

    暂无相关文章