问题
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