繁体   English   中英

Apache.commons.cli命令行参数

[英]Apache.commons.cli Command Line Arguments

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

防爆。

  1. myprogram作业-dryrun
  2. myprogram作业-更新
  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'

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

        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());
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM