一、介绍
Commons CLI库是apache的一个子项目,比较起来,其使用方法相对规范。 http://commons.apache.org/proper/commons-cli/
Commons CLI supports different types of options:
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)
A typical help message displayed by Commons CLI looks like this:
usage: ls
-A,--almost-all do not list implied . and ..
-a,--all do not hide entries starting with .
-B,--ignore-backups do not list implied entried ending with ~
-b,--escape print octal escapes for nongraphic characters
--block-size use SIZE-byte blocks
-c with -lt: sort by, and show, ctime (time of last
modification of file status information) with
-l:show ctime and sort by name otherwise: sort
by ctime
-C list entries by columns
二、例子
package Test;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
public class CLITest {
public static void main(String[] args) throws ParseException {
Options options = new Options();
//短选项,长选项,选项后是否有参数,描述
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("h", "help", false, "display help text");
options.addOption(option);
//CommandLineParser parser = new PosixParser();//Posix风格
CommandLineParser parser = new GnuParser();//gun风格
CommandLine commandLine = parser.parse(options, args);
//判断
if (commandLine.hasOption('h')) {
//格式化输出
new HelpFormatter().printHelp("flume-ng agent", options, true);
return;
}
if (commandLine.hasOption('f')) {
//获取参数
String file = commandLine.getOptionValue('f');
}
}
}