Contact at or 8097636691
Responsive Ads Here

Sunday, 1 July 2018

Apache Commons CLI - Boolean Option

Apache Commons CLI - Boolean Option

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.

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);


Run the file without passing any option and see the result.
java CLITester 
Run the file while passing -t as option and see the result.
java CLITester 
12/11/2017 4:13:10

No comments:

Post a Comment