Apache Commons CLI是开源的命令行解析工具,它可以帮助开发者快速构建启动命令,并且帮助你组织命令的参数、以及输出列表等。
CLI分为三个过程:
- 定义阶段:在Java代码中定义Optin参数,定义参数、是否需要输入值、简单的描述等
- 解析阶段:应用程序传入参数后,CLI进行解析
- 询问阶段:通过查询CommandLine询问进入到哪个程序分支中
一、定义:
Option opt = new Option("h", "help", false, "Print help");
opt.setRequired(false);
options.addOption(opt);
参数介绍:
- 第一个参数:参数的简单形式
- 第二个参数:参数的复杂形式
- 第三个参数:是否需要额外的输入
- 第四个参数:对参数的描述信息
二、解析:
CommandLine commandLine = null;
CommandLineParser parser = new PosixParser();
try {
commandLine = parser.parse(options, args);
}catch(Exception e){
System.exit(1);
}
三、询问:
HelpFormatter hf = new HelpFormatter();
hf.setWidth(110);
if (commandLine.hasOption('h')) {
hf.printHelp("commandLine test", options, true);
System.exit(0);
}