Java 使用 Apache 公共库的命令行参数解析问题

Java Command line argument parsing issue using Apache commons library

我正在使用 Apache commons basic/gnu 解析器来解析命令行选项,如下所示。

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

我正在使用下面提到的参数列表调用程序。

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

我得到的输出只是第一个 IP 地址,我怎样才能得到所有三个 IP 地址和端口作为参数传递给 --iplist 变量?

这是我正在使用的选项。

    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
       }

您可以像这样使用 OptionBuilder

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()

另请参阅:

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