
commons-CLI.png
背景
Apache Commons CLI包用于解析命令行参数,并可以打印命令行help信息。
支持以下类型:
- POSIX like options (ie. tar -zxvf foo.tar.gz)
- GNU like long options (ie. du --human-readable --max-depth=1)
- Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
- Short options with value attached (ie. gcc -O2 foo.c)
- long options with single hyphen (ie. ant -projecthelp)
在阅读flume源码时,发现它的命令行解析用的就是commons-cli。
实操
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
package com.example.note;
import java.util.Properties;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CommonCliTest {
public static void main(String[] args) throws ParseException {
Options options = new Options();
// 有两种方式 -n 或者 --name
Option option = new Option("n", "name", true, "the name of this agent");
option.setRequired(true);// 必填
options.addOption(option);
option = new Option("f", "conf-file", true, "specify a config file (required if -z missing)");
option.setRequired(false);// 选填
options.addOption(option);
option = new Option(null, "no-reload-conf", false, "do not reload config file if changed");
options.addOption(option);
option = new Option("h", "help", false, "display help text");
options.addOption(option);
//java -Dcom.example.db=order
option = Option.builder("D").argName("property=name").hasArgs().valueSeparator().desc("use value for a property").longOpt(null).build();
options.addOption(option);
CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(options, args);
if (commandLine.hasOption('h')) {
// 打印help信息
new HelpFormatter().printHelp("flume-ng agent", options, true);
return;
}
// 获取命令行参数
String agentName = commandLine.getOptionValue('n');
System.out.println(agentName);
Properties properties = commandLine.getOptionProperties("D");
System.out.println(properties);
}
}
输入 flume-ng agent -n game -f /app/flume/conf/game.conf
可以获得name为game,file为/app/flume/conf/game.conf