Trying to use Apache Commons Command Line Interface 1.3.1
from here It works fine for required arguments, but seems to drop any optional arguments. Can anyone spot a problem with my code below?
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class TestCommandLine {
public static void main(String[] args) {
// ***** test with command line arguments -R myfirstarg -O mysecondarg *****
// ***** the second arg is not being captured *****
System.out.println("Number of Arguments : " + args.length);
String commandline = "";
for (String arg : args) {
commandline = commandline + (arg + " ");
}
commandline.trim();
System.out.println("Command-line arguments: " + commandline);
// create Options object
Options options = new Options();
options.addOption("R", true, "Enter this required argument");
Option optionalargument = Option.builder("O")
.optionalArg(true) // if I change this line to .hasArg(true) it works, but then is not optional
.desc("Enter this argument if you want to")
.build();
options.addOption(optionalargument);
// initialize variables used with command line arguments
String firstargument = null;
String secondargument = null;
CommandLineParser parser = new DefaultParser();
try {
// parse the command line arguments
CommandLine cmd = parser.parse( options, args );
firstargument = cmd.getOptionValue("R");
secondargument = cmd.getOptionValue("O");
if(cmd.hasOption("R")){
if(firstargument == null){
System.out.println("Must provide the first argument ... exiting...");
System.exit(0);
}
else {
System.out.println("First argument is " + firstargument);
}
}
if(cmd.hasOption("O")) {
// optional argument
if (secondargument == null){
System.out.println("Second argument is NULL");
}
else{
// should end up here if optional argument is provided, but it doesn't happen
System.out.println("Second argument is " + secondargument);
}
}
}
catch( ParseException exp ) {
// oops, something went wrong
System.err.println( "Parsing failed. Reason: " + exp.getMessage() );
}
}
}
The output from the above code is:
Number of Arguments : 4
Command-line arguments: -R myfirstarg -O mysecondarg
First argument is myfirstarg
Second argument is NULL
Why isn't "mysecondarg" being captured? If I change the line .optionalArg(true) to .hasArg(true), then the second argument is captured, but the whole idea is to be able to optionally leave the second argument out.
It seems you need to set numberOfArgs in addition to hasOptionalArgs in order for it to work properly.