3

M tryng 使用 apache commons cli ,我的用例是带有一些选项的可变数量的参数。

 -p str1 str2;

有可能

 -p str1 str2 str3 .. strn

另一个是

 -m str1
 -h

 cmdline.getOptionValues("p");

它只获取最后一个字符串。如何获取特定选项的所有值?

编辑:

if(cmdline.hasOption("p")){
 String[] argsList = cmdline.getOptionValues(p);
  String strLine = Arrays.toString(argsList);
  argsList = strLine.split(",");
 }

我做对了吗?字符串是否会包含我想要的确切数据或smthng 意外的空格或其他任何内容?

4

2 回答 2

4

hasArgs()与设置为逗号的值分隔符一起使用,因此选项变为

-p str1,str2,str3,...,strn

这就是在 CLI 中处理多值选项的方式

于 2014-04-24T06:52:22.353 回答
1

我并不完全清楚你在做什么以及“它返回错误”的位置,但这应该有效,我认为做你想做的事情。

final CommandLineParser cmdLinePosixParser = new PosixParser();
Options options = new Options();
options.addOption(OptionBuilder.withArgName("p").hasArgs().create("p"));
CommandLine commandLine = cmdLinePosixParser.parse(options, args);
if (commandLine.hasOption("p")) {
    String[] pArgs = commandLine.getOptionValues("p");
    System.out.println(pArgs.length);
    for (String p : pArgs) {
        System.out.println(p);
    }
}
于 2014-04-24T11:30:15.383 回答