command line parsing using apache commons cli

青春壹個敷衍的年華 提交于 2019-12-22 10:53:16

问题


M tryng to use apache commons cli , My use case is variable number of arguments with some options.

Say

 -p str1 str2;

It can be

 -p str1 str2 str3 .. strn

Another is

 -m str1
 -h

with

 cmdline.getOptionValues("p");

It fetches only last string.How can I fetch all the values of an particular option?

Edit:

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

M i doing it right? will string consist of exactly data I want or smthng unexpected white spaces r anythng else?


回答1:


Use hasArgs() with a value separator set to a comma, so the option becomes

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

This is how multi-valued options are handled in CLI




回答2:


It's not entirely clear to me what you're doing and where "it returns false", but this should work and I think do what you're trying to do.

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


来源:https://stackoverflow.com/questions/23261629/command-line-parsing-using-apache-commons-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!