【问题标题】:Apache Commons CLI argument valueApache Commons CLI 参数值
【发布时间】:2014-08-14 18:00:32
【问题描述】:

我正在尝试编写一个执行时的程序 java -jar -cf 文件.txt 将检索 cf 参数的值。我到目前为止的代码是:

Options options = new Options();

final Option configFileOption = Option.builder("cf")
                        .longOpt("configfile")
                        .desc("Config file for Genome Store").argName("cf")
                        .build();

options.addOption(configFileOption);

CommandLineParser cmdLineParser = new DefaultParser();
CommandLine commandLineGlobal= cmdLineParser.parse(options, commandLineArguments);

if(commandLineGlobal.hasOption("cf")) {
        System.out.println(commandLineGlobal.getOptionValue("cf"));
    }

我面临的问题是正在打印的值为空。谁能告诉我我错过了什么?

【问题讨论】:

    标签: apache-commons-cli


    【解决方案1】:

    找出它为什么不起作用的一个有用方法是打印出commons-cli的帮助信息

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp( "sample", options );
    

    打印出来

    usage: sample
     -cf,--configfile   Config file for Genome Store
    

    这表明您使用 longOpt() 为选项指定别名,而不是 arg 值。执行您想要的操作的正确代码是:

        final Option configFileOption = Option.builder("cf")
                                .argName("configfile")
                                .hasArg()
                                .desc("Config file for Genome Store")
                                .build();
    

    正确打印

    usage: sample
     -cf <configfile>   Config file for Genome Store
    

    并将传递的参数也正确报告给 -cf。

    有关详细信息,请参阅javadoc of the Option class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2016-02-25
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      相关资源
      最近更新 更多