Friday, 16 December 2016

Commons CLI : Options class

It is the main entry point to the Commons CLI library.  By using Options class, you can link number of options available to any command.

Options class provide overloading form of ‘addOption’ method to link multiple options.

public Options addOption(String opt, String description)
public Options addOption(String opt, boolean hasArg, String description)
public Options addOption(String opt, String longOpt, boolean hasArg, String description)
public Options addOption(Option option)

Find the description about the arguments of adoption method below.

opt: Short single-character name of the option.
longOpt: Long multi-character name of the option.
description: Self-documenting description
hasArg: flag specifies if an argument is required after this option
option: Option instance to be added

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").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>] [-c]
     -A,--almost-all            do not list implied . and ..
     -b,--block-size <SIZE>     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






Previous                                                 Next                                                 Home

No comments:

Post a Comment