2014-06-12 100 views
2

想要使用Optionapache.commons.cli)作为命令和子命令。Apache.commons.cli命令行参数

Ex。

  1. myprogram工作-dryrun
  2. myprogram工作-update
  3. myprogram工作-UPDATE -dryrun

什么是做这种方式吗?

试图用简单的程序:

public static void main(String[] args) throws ParseException { 
    test("job", "-update"); //works fine 
    test("job", "-dryrun"); //works fine 
    test("job", "-update", "-dryrun"); // doesn't work 
} 
public static void test(String... args) throws ParseException { 
    GnuParser parser = new GnuParser(); 
    Options options = new Options(); 
    OptionGroup option = new OptionGroup(); 
    option.addOption(new Option("dryrun", "dryrun")); 
    option.addOption(new Option("update", "update")); 
    options.addOptionGroup(option); 
    parser.parse(options, args); 
} 

错误:

test("job", "-update", "-dryrun"); 
fails with, Exception in thread "main" org.apache.commons.cli.AlreadySelectedException: The option 'dryrun' was specified but an option from this group has already been selected: 'update' 

回答

0

你为什么使用选项组?您可以使用OptionBuilder请参阅Commons CLI使用场景http://commons.apache.org/proper/commons-cli/usage.html有关工作项目的完整代码,请参阅https://github.com/firefoxNX/StackOverflow/tree/master/CommonsCli

 Options options = new Options(); 
     Option dryrunOption = OptionBuilder.withArgName("dryrun") 
       .withDescription("dry run").create("dryrun"); 
     options.addOption(dryrunOption); 

     Option updateOption = OptionBuilder.withArgName("update") 
       .withDescription("update").create("update"); 
     options.addOption(updateOption); 

     // create the parser 
     GnuParser parser = new GnuParser(); 
      // parse the command line arguments 
      CommandLine line = parser.parse(options, args); 
      Option[] opts = line.getOptions(); 
      for(String arg: line.getArgs()){ 
       System.out.println(arg); 
      } 
      for(Option opt: opts){ 
       System.out.println(opt.getOpt()+" : "+opt.getValue()); 
      }