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