目录

Commons CLI - 布尔选项( Boolean Option)

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

例子 (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)

在不传递任何选项的情况下运行该文件并查看结果。

java CLITester 
12/11/2017

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

java CLITester 
12/11/2017 4:13:10
↑回到顶部↑
WIKI教程 @2018