Friday, 16 December 2016

Commons-CLI: Setting the compulsory options

For any given command there two types of options.
a.   Mandatory options to execute a command
b.   Optional (not mandatory) options to execute a command.

FileCopy -i <FILE PATH> -o <FILE PATH> [-lang <LANGUAGE>]

Notify above command, -I, -o are mandatory arguments to the command FileCopy, where as lang is optional. Option class provide 'setRequired' method, by setting this argument to true, you can make the argument compulsory.

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.setOptionComparator(null);
  helpFormatter.printHelp(writer, width, cmdLineSyntax, header, options, leftPad, descPad, footer, autoUsage);
  writer.flush();
 }

 public static void main(String args[]) {

  Options options = new Options();

  Option input = new Option("i", "input", true, "input file to read data from");
  input.setRequired(true);
  input.setArgName("FILE PATH");
  options.addOption(input);

  Option output = new Option("o", "output", true, "output file to write the final result");
  output.setRequired(true);
  output.setArgName("FILE PATH");
  options.addOption(output);

  Option language = new Option("lang", "language", true, "Encoding Langauge");
  language.setArgName("LANGUAGE");
  options.addOption(language);

  printHelp(options, 100, "FileCopy", "", "", 5, 5, true, System.out);

 }
}

Output
usage: FileCopy -i <FILE PATH> -o <FILE PATH> [-lang <LANGUAGE>]
     -i,--input <FILE PATH>          input file to read data from
     -o,--output <FILE PATH>         output file to write the final result
     -lang,--language <LANGUAGE>     Encoding Langauge





Previous                                                 Next                                                 Home

No comments:

Post a Comment