Friday 16 December 2016

Commons-CLI Define options using builder

Option class provides builder to define options. If an object has more properties to initialize, builder design pattern is used to instantiate object conveniently.


Example
Option option1 = Option.builder("A").longOpt("almost-all").desc("do not list implied . and ..").hasArg(false).build();

Following is the complete working application.

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