Apache Commons CLI - Usage Example



Overview

Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. Consider the following usage to be printed when we used the application without passing any argument.

java CLITester
usage: CLITester [-g] [-n <arg>] [-p]

Define the Options

options.addOption("p", "print", false, "Send print request to printer.")
   .addOption("g", "gui", false, "Show GUI Application")
   .addOption("n", true, "No. of copies to print");

Print the usage using HelpFormatter

System.out.println("usage: CLITester " + formatter.toSyntaxOptions(options));

Example - Printing usage on command line arguments

In this example, we're printing usage using HelpFormatter if no argument is passed.

CLITester.java

package com.tutorialspoint;

import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.help.HelpFormatter;

public class CLITester {
   public static void main(String[] args) throws ParseException, IOException {
	
      Options options = new Options();
      options.addOption("p", "print", false, "Send print request to printer.")
         .addOption("g", "gui", false, "Show GUI Application")
         .addOption("n", true, "No. of copies to print");
			
      String header = "Welcome to CLI Application";
      String footer = "Please report issues at https://tutorialspoint.com/issues";

      HelpFormatter formatter = HelpFormatter.builder().get();
	  
      // Create a parser
      CommandLineParser parser = new DefaultParser();

      // parse the options passed as command line arguments
      CommandLine cmd = parser.parse( options, args);

      // hasOptions checks if option is present or not
      if(cmd.hasOption("p")) {
         // do printing
      }
      else if(cmd.hasOption("g")) {
         // show gui
      }else if (cmd.hasOption("n")) {
         // get no. of copies
      }else {
         // print usage
    	  System.out.println("usage: CLITester " + formatter.toSyntaxOptions(options));
      }
   }
}

Output

Run the file, without passing any argument and see the result −

java CLITester 
usage:  CLITester [-g] [-n <arg>] [-p]
Advertisements