Apache Commons CLI - Boolean Option


Advertisements

A boolean option is represented on a command line by its presence. For example, if option is present then its value is true otherwise it is considered as false. Consider the following example, where we're printing current date and if -t flag is present then we'll print time too.

Example

CLITester.java

import java.util.Calendar;
import java.util.Date;

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;

public class CLITester {
   public static void main(String[] args) throws ParseException {
      Options options = new Options();
      options.addOption("t", false, "display time");

      CommandLineParser parser = new DefaultParser();
      CommandLine cmd = parser.parse( options, args);

      Calendar date = Calendar.getInstance();
      int day = date.get(Calendar.DAY_OF_MONTH);
      int month = date.get(Calendar.MONTH);
      int year = date.get(Calendar.YEAR);

      int hour = date.get(Calendar.HOUR);
      int min = date.get(Calendar.MINUTE);
      int sec = date.get(Calendar.SECOND);

      System.out.print(day + "/" + month + "/" + year);
      if(cmd.hasOption("t")) { 
         System.out.print(" " + hour + ":" + min + ":" + sec);
      }
   }
}

Output

Run the file without passing any option and see the result.

java CLITester 
12/11/2017

Run the file while passing -t as option and see the result.

java CLITester 
12/11/2017 4:13:10
Advertisements