java - How to get Apache CLI to handle double-dash? -
java - How to get Apache CLI to handle double-dash? -
i've looked @ docs can't see how apache commons cli handle double-hyphen "option" terminates alternative processing.
consider next command-line has "-opt" alternative can take optional argument not specified:
myprogram -opt -- param1 param2
i want alternative end no arguments in case, apache returns "--" argument. if alternative allowed more 1 argument, or of parameters returned arguments.
here sample code illustrating issue:
package com.lifetouch.commons.cli; import java.util.arrays; import org.apache.commons.cli.*; public class doublehyphen { private static options options = new options(); public static void main(string args[]) { // 1 required alternative optional argument: @suppresswarnings("static-access") optionbuilder builder = optionbuilder.isrequired(true). withdescription("one optional arg"). withargname("optarg").hasoptionalargs(1); options.addoption(builder.create("opt")); // illustrate issue: doclitest(new string[] { "-opt"} ); doclitest(new string[] { "-opt", "optarg", "param"} ); doclitest(new string[] { "-opt", "--", "param"} ); // want double-dash terminate alternative processing. // note if "opt" used hasoptionalargs(2) "param" sec // argument alternative (rather application parameter). } private static void doclitest(string[] args) { system.out.println("\ntest case -- command line items: " + arrays.tostring(args)); // parse command line: commandline cmdline = null; seek { commandlineparser parser = new gnuparser(); cmdline = parser.parse(options, args); // using stopatnonoption not help } grab (parseexception ex) { system.err.println("command line parse error: " + ex); return; } // observe results alternative , argument: string optargs[] = cmdline.getoptionvalues("opt"); if (null == optargs) { system.out.println("no args specified opt"); } else { system.out.println(optargs.length + " arg(s) -opt option: " + arrays.tostring(optargs)); } // observe results command-line parameters: string tmp = arrays.tostring(cmdline.getarglist().toarray()); system.out.println(cmdline.getarglist().size() + " command-line parameter(s): " + tmp); } }
in order handle special token --
alternative terminator, must utilize posix parser.
use
commandlineparser parser = new posixparser();
instead of
commandlineparser parser = new gnuparser();
java command-line-interface apache-commons apache-commons-cli
Comments
Post a Comment