Reputation: 838
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?
Upvotes: 2
Views: 4214
Reputation: 15872
A useful method to find out why it does not work is to print out the help-information of commons-cli
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "sample", options );
this prints
usage: sample
-cf,--configfile Config file for Genome Store
Which indicates that with longOpt() you are specifying an alias for the option, not the arg-value. The correct code to do what you want is:
final Option configFileOption = Option.builder("cf")
.argName("configfile")
.hasArg()
.desc("Config file for Genome Store")
.build();
which correctly prints
usage: sample
-cf <configfile> Config file for Genome Store
and reports the passed argument to -cf correctly as well.
See the javadoc of the Option class for more details.
Upvotes: 6