2

I am trying to write a program which when executed java -jar -cf file.txt will retrieve the value of the cf argument. The code I have so far is:

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

The problem I am facing is that the value which is being printed is null. Could anyone tell me what I am missing?

4

1 回答 1

6

找出它为什么不起作用的一个有用方法是打印出 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。

有关更多详细信息,请参阅Option 类的 javadoc 。

于 2014-08-16T07:23:29.013 回答