I
don’t find any direct way to build an option with multiple arguments. By using argName
and numberOfArgs method of Option builder, we can set multiple arguments to an
option.
Example
Option
option2 =
Option.builder("b").longOpt("block-size").argName("SIZE>
<CAPACITY> <LINE").numberOfArgs(3).desc("use SIZE-byte
blocks").hasArg(true).build();
Above
snippet generates following option.
-b,--block-size
<SIZE> <CAPACITY> <LINE>> use SIZE-byte blocks
Find
complete working application below.
OptionDemo.java
import java.io.OutputStream; import java.io.PrintWriter; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; public class OptionDemo { public static void printHelp(final Options options, final int width, final String cmdLineSyntax, final String header, final String footer, final int leftPad, final int descPad, final boolean autoUsage, final OutputStream out) { PrintWriter writer = new PrintWriter(out); final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(writer, width, cmdLineSyntax, header, options, leftPad, descPad, footer, autoUsage); writer.flush(); } public static void main(String args[]) { Option option1 = Option.builder("A").longOpt("almost-all").desc("do not list implied . and ..").hasArg(false).build(); Option option2 = Option.builder("b").longOpt("block-size").argName("SIZE> <CAPACITY> <LINE").numberOfArgs(3).desc("use SIZE-byte blocks").hasArg(true).build(); Option option3 = Option.builder("c").desc("with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime").hasArg(false).build(); Options options = new Options(); options.addOption(option1).addOption(option2).addOption(option3); printHelp(options, 100, "ls", "", "", 5, 5, true, System.out); } }
Output
usage: ls [-A] [-b <SIZE> <CAPACITY> <LINE>] [-c] -A,--almost-all do not list implied . and .. -b,--block-size <SIZE> <CAPACITY> <LINE> use SIZE-byte blocks -c with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime
No comments:
Post a Comment