Search code examples
javacommand-line-argumentsapache-commons-cli

Java Command line argument parsing issue using Apache commons library


I am using Apache commons basic/gnu parser to parse command line options as shown below.

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.GnuParser;


    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    System.out.println(cmd.getOptionValue("iplist"));

I am invoking program using below mention list of parameters.

 java -jar myjar.jar --iplist 160.1.1.1,3009 160.1.1.1,3003 160.1.1.1,3004

Out put i am getting is just first IP address, how can i get all three IP addresses with port which are passed as an argument to --iplist variable?

Here are the options i am using.

    options.addOption("h", "help", false, "show help.");
    options.addOption("iplst","iplist", true, "Provide name of server where program can listen IP,PORT");

         CommandLineParser parser = new GnuParser();
         CommandLine cmd = null;
      try {
       cmd = parser.parse(options, args);

       if (cmd.hasOption("h"))
        help();

       if (cmd.hasOption("iplist")) {
        System.out.println( "Using cli argument --server=" + cmd.getOptionValue("iplistr"));
//Code here
       }

Solution

  • You can use OptionBuilder like:

    Option iplist = OptionBuilder
                    .withArgs() // option has unlimited argument
                    .withDescription("Provide name of server where program can listen IP,PORT")
                    .withLongOption("iplist") // means start with -- 
                    .create()
    

    Also look at:

    https://commons.apache.org/proper/commons-cli/usage.html

    http://apache-commons.680414.n4.nabble.com/cli-Example-using-of-option-with-two-mandatory-arguments-td3321524.html