Commons Cli 简明教程

Apache Commons CLI - Boolean Option

布尔选项在命令行中由其存在表示。例如,如果存在选项,那么其值为 true,否则,其会被视为 false。考虑以下示例,其中我们输出当前日期,如果存在 -t 标志。那么,我们还将输出时间。

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 are printing current date and if -t flag is present. Then, we will print time too.

Example

CLITester.java

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

在将 -t 作为选项传递的同时运行该文件,然后查看结果。

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

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