Apache Commons CLI - 布尔选项

布尔选项在命令行上由其存在表示.例如,如果存在选项,则其值为true,否则将其视为false.考虑以下示例,我们打印当前日期,如果存在-t标志,那么我们也将打印时间.

示例

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

输出

运行文件而不通过任何选项并查看结果.

java CLITester 
12/11/2017

运行文件时传递-t作为选项并查看结果.

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