Skip to content
Advertisement

Java commons cli parser not recognizing command line arguments

This should be very simple but I am not sure why its not working. I am trying pass arguments with a name (So I can pass arguments in any order) using the apache commons CLI library but It seems to be not working. I want to pass the arguments from eclipse IDE. I know this part is not the problem because I am able to print the arguments with args[0] kind.

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class MainClass {

public static void main(String[] args) throws ParseException {
    System.out.println(args[0]);
    Options options = new Options();
    options.addOption("d", false, "add two numbers");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse( options, args);
    if(cmd.hasOption("d")) {
        System.out.println("found d");
    } else {
        System.out.println("Not found");
    }
}

The above lines are exactly like the examples given online but i dont know why its not working. I am struggling this from a day now. Please help where I am going wrong.

Advertisement

Answer

According to the examples name of the parameter should be present in command line

Property without value

Usage: ls [OPTION]... [FILE]...
-a, --all                  do not hide entries starting with .

And the respective code is:

// create the command line parser
CommandLineParser parser = new DefaultParser();

// create the Options
Options options = new Options();
options.addOption( "a", "all", false, "do not hide entries starting with ." );

In this scenario correct call is:

ls -a or ls --all

With value separated by space

-logfile <file>        use given file for log

Respective code is:

Option logfile   = OptionBuilder.withArgName( "file" )
                                .hasArg()
                                .withDescription(  "use given file for log" )
                                .create( "logfile" );

And call would be:

app -logfile name.of.file.txt

With value separated by equals

-D<property>=<value>   use value for given property

The code is:

Option property  = OptionBuilder.withArgName( "property=value" )
                                .hasArgs(2)
                                .withValueSeparator()
                                .withDescription( "use value for given property" )
                                .create( "D" );

And call would be:

app -Dmyprop=myvalue
Advertisement