Apache Commons CLI - 布尔选项
布尔选项在命令行上通过其存在来表示。例如,如果 option 存在,则其值为 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