首先需要说明,在1.3版本之前,主要使用的是BasicParser类,根据源码文档说明,它只是对抽象类Parser的简单实现,功能有限。自1.3版本之后,我们改用DefaultParser类。
就使用者在编码方面而言,基本没有区别,下面进行演示:
首先在pom.xml中引入依赖:
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
然后,上代码:
import org.apache.commons.cli.*;
public class CliDemo {
public static void main(String[] args) throws ParseException {
// 短选项名,可通过-f指定
String opt = "f";
// 长选项名,可通过--file指定
String longOpt = "file";
// 选项文字说明
String description = "文件";
// 过时API,版本<1.3
// BasicParser parser = new BasicParser();
// 版本1.3+,取代BasicParser
DefaultParser parser = new DefaultParser();
Options options = new Options();
// 添加选项
options.addOption(opt, longOpt, true, description);
// 通过选项名获取选项
Option fileOption = options.getOption(opt);
// 对参数数组进行拆分,获取到命令行对象
CommandLine commandLine = parser.parse(options, args);
// 命令行判断选项和取值
if (!commandLine.hasOption(opt)) {
System.err.println(String.format("%s 未传入,程序运行失败。", fileOption.getDescription()));
System.out.println(String.format("Usage: java -jar xxx.jar -%s pathStr", opt));
System.exit(-1);
}
String param = commandLine.getOptionValue(opt);
System.out.println(param);
}
}