1.Commons CLI

Apache Commons CLI提供了解析命令行参数的API,命令行的处理共分为三个阶段:定义阶段、解析阶段和审讯阶段。它也可以在命令行打印详细的参数信息。
官网教程:http://commons.apache.org/proper/commons-cli/usage.html,
Commons CLI的Javadoc:http://commons.apache.org/proper/commons-cli/javadocs/api-release/index.html。

Commons CLI提供了一下不同类型的参数形式

POSIX(Portable Operating System Interface of Unix)形式,如:tar -zxvf foo.tar.gz
GNU中长参数形式,如:du --human-readable --max-depth=1
Java命令中的参数形式,如:java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo
短杠带参数值的形式,如:gcc -O2 foo.c
长杠不带参数值的形式,如:ant – projecthelp

2.CLI定义阶段

Apache Commons CLI使用Options这个类来定义和设置参数,它是所有参数的容器。它提供了下面几种方法添加参数:

addOption(Option opt)addOption(String opt, boolean hasArg, String description)addOption(String opt, String description)addOption(String opt, String longOpt, boolean hasArg, String description)

第二和第三个方法用于添加短名称(或名称缩写)参数,第四个方法还提供了长名称参数。而其中的boolean参数为true时,当调用getOptionValue()方法时,可以返回对应的参数只;反之,为false时,返回null。

其中,第一个方法要更复杂些。需要先创建一个Option对象,Option对象是由OptionBuilder创建的。如:

Option filesOption = OptionBuilder.withArgName("args").withLongOpt("files").hasArgs(2).withValueSeparator(',').withDescription("file names").create("f");

hasArgs()方法指定参数后有几个值,withValueSeparator(char seq)指定参数值之间的分隔符。

在定义阶段,我们需要使用Options类来定义我们需要使用的命令。

方法摘要:

返回值 方法名 说明
Options addOption(Option opt) 添加一个选项实例
Options addOption(String opt, boolean hasArg, String description) 添加一个只包含短名称的选项
Options addOption(String opt, String description) 添加一个只包含短名称的选项
Options addOption(String opt, String longOpt, boolean hasArg, String description) 添加一个包含短名称和长名称的选项
Options addOptionGroup(OptionGroup group) 添加一个选项组
List<String> getMatchingOptions(String opt) 获得匹配选项的长名称集合
Option getOption(String opt) 通过长名称或短名称获得选项
OptionGroup getOptionGroup(Option opt) 获得选项所在的选项组
Collection getOptions() 获得一个只读的选项集合
List getRequiredOptions() 获得必须的选项集合
boolean hasLongOption(String opt) 判断是否存在选项
boolean hasOption(String opt) 判断是否存在选项
boolean hasShortOption(String opt) 判断是否存在选项

3.CLI解析阶段

在解析阶段中,通过命令行传入应用程序的文本来进行处理。处理过程将根据在解析器的实现过程中定义的规则来进行。Commons CLI提供了一个接口CommandLineParser,而且分别实现了下面几种解析器,用于不同的场景:

DefaultParser:提供了很基础的解析功能,只能解析基础的命令行参数。
BasicParser:提供了基础的解析功能,能解析简单的命令行参数。
PosixParser:提供了解析POSIX形式参数的功能。
GnuParser:提供了解析长参数及Java命令中参数的功能。
CommandLineParser parser = new PosixParser();
CommandLine cli = parser.parse(options, args);

在解析阶段,我们需要使用DefaultParser来解析命令行参数。DefaultParser实现了CommandLineParser接口,解析命令行参数完成后会返回CommandLine对象,在审讯阶段,我们就需要CommandLine对象来完成我们实际的工作。

部分方法摘要:

返回值 方法名 说明
List getArgList() 获得参数集合
String[] getArgs() 获得参数数组
Option[] getOptions() 获得选项数组
String getOptionValue(char opt) 获得选项值
String getOptionValue(char opt, String defaultValue) 获得选项值
String getOptionValue(String opt) 获得选项值
String getOptionValue(String opt, String defaultValue) 获得选项值
boolean hasOption(char opt) 判断是否含有选项
boolean hasOption(String opt) 判断是否含有选项

4.CLI询问阶段

在询问阶段中,应用程序通过查询 CommandLine,并通过其中的布尔参数和提供给应用程序的参数值来决定需要执行哪些程序分支。这个阶段在用户的代码中实现,CommandLine 中的访问方法为用户代码提供了 CLI 的询问能力。
CLI 询问阶段的目标结果就是将所有通过命令行以及处理参数过程中得到的文本信息传递给用户的代码。

if(cli.hasOption("h")) {HelpFormatter hf = new HelpFormatter();hf.printHelp("Options", options);
}

5.CLI使用

5.1CLI配置

要使用Commons CLI需要将其JAR加入到CLASSPATH,或者如下添加Maven依赖:

<dependency><groupId>commons-cli</groupId><artifactId>commons-cli</artifactId><version>${cli-version}</version>
</dependency>

5.2Basic Parser

BasicParser和DefaultParser只能解析基础的命令行参数,如:

public static void basicParseCLI(String[] args){Options options = new Options();options.addOption("h", "help", false, "print options' information");options.addOption("d", "database", true, "name of a database");options.addOption("t", true, "name of a table");Option filesOption = OptionBuilder.withArgName("args").withLongOpt("files").hasArgs().withDescription("file names").create("f");options.addOption(filesOption);//  CommandLineParser parser = new DefaultParser();CommandLineParser parser = new BasicParser();try {CommandLine cli = parser.parse(options, args);if(cli.hasOption("h")){HelpFormatter hf = new HelpFormatter();hf.printHelp("Options", options);}else {String database = cli.getOptionValue("d");System.out.println("database: " + database);String table = cli.getOptionValue("t");System.out.println("table: " + table);String[] files = cli.getOptionValues("f");System.out.println("files: " + Arrays.asList(files));}}catch (Exception e){e.printStackTrace();}
}

命令行参数:

-d database -t table -files file1 file2
-database database -t table -files file1 file2

输出:

database: database
table: table
files: [file1, file2]

5.3POSIX Parser

PosixParser可以解析POSIX形式的命令行参数和Java命令中参数形式,如:

public static void posixParseCLI(String[] args){Options options = new Options();options.addOption("h", "help", false, "print options' information");options.addOption("d", "database", true, "name of a database");options.addOption("t", true, "name of a table");Option filesOption = OptionBuilder.withArgName("args").withLongOpt("files").hasArgs().withDescription("file names").create("f");options.addOption(filesOption);// hasArgs()指定后跟参数值得个数Option property = OptionBuilder.withArgName("property=name").hasArgs().withValueSeparator().withDescription("use value for a property").create("D");options.addOption(property);CommandLineParser parser = new PosixParser();try {CommandLine cli = parser.parse(options, args);if(cli.hasOption("h")){HelpFormatter hf = new HelpFormatter();hf.printHelp("Options", options);}else {String database = cli.getOptionValue("d");System.out.println("database: " + database);String table = cli.getOptionValue("t");System.out.println("table: " + table);String[] files = cli.getOptionValues("f");System.out.println("files: " + Arrays.asList(files));Properties properties = cli.getOptionProperties("D");String ext = properties.getProperty("ext");System.out.println("property ext = " + ext);}}catch (Exception e){e.printStackTrace();}
}

命令行参数:

-d database -ttable -files file1 file2 -Dext=java

输出:

database: database
table: table
files: [file1, file2]
property ext = java

5.4GNU Parser

GnuParser可以解析长参数及Java命令中参数,如:opt=value。

public static void gnuParseCLI(String[] args){Options options = new Options();options.addOption("h", "help", false, "print options' information");options.addOption("d", "database", true, "name of a database");options.addOption("t", true, "name of a table");// withValueSeparator(char sep)指定参数值之间的分隔符Option filesOption = OptionBuilder.withArgName("args").withLongOpt("files").hasArgs().withValueSeparator(',').withDescription("file names").create("f");options.addOption(filesOption);Option property = OptionBuilder.withArgName("property=name").hasArgs().withValueSeparator().withDescription("use value for a property").create("D");options.addOption(property);CommandLineParser parser = new GnuParser();try {CommandLine cli = parser.parse(options, args);if(cli.hasOption("h")){HelpFormatter hf = new HelpFormatter();hf.printHelp("Options", options);}else {String database = cli.getOptionValue("database");System.out.println("database: " + database);String table = cli.getOptionValue("t");System.out.println("table: " + table);String[] files = cli.getOptionValues("f");System.out.println("files: " + Arrays.asList(files));Properties properties = cli.getOptionProperties("D");String ext = properties.getProperty("ext");String dir = properties.getProperty("dir");System.out.println("property ext: " + ext + "\tdir:" + dir);}}catch (Exception e){e.printStackTrace();}
}

命令行参数:

--database=database -t table --files=file1,file2 -Dext=java -Ddir=dir

输出:

database: database
table: table
files: [file1, file2]
property ext: java dir:dir

commons-cli使用介绍相关推荐

  1. 使用 Apache Commons CLI 开发命令行工具

    http://www.ibm.com/developerworks/cn/java/j-lo-commonscli/index.html 使用 Apache Commons CLI 开发命令行工具 杨 ...

  2. Java命令行界面(第1部分):Apache Commons CLI

    尽管我通常使用Groovy编写要从命令行运行的JVM托管脚本,但是有时候我需要解析Java应用程序中的命令行参数,并且有很多库可供Java开发人员用来解析命令行参数. 在本文中,我将介绍这些Java命 ...

  3. commons-io_从Commons CLI迁移到picocli

    commons-io 最初于2002年发布的Apache Commons CLI可能是使用最广泛的Java命令行解析器,但是它的API显示了它的年龄. 寻找具有最少样板代码的现代方法的应用可能对pic ...

  4. flink报错org.apache.commons.cli.Option.builder

    问题复现: yarn-session.sh 完整报错如下: SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found bindi ...

  5. commons cli_从Commons CLI迁移到picocli

    commons cli 最初于2002年发布的Apache Commons CLI可能是使用最广泛的Java命令行解析器,但是它的API显示了它的年龄. 寻找具有最少样板代码的现代方法的应用可能对pi ...

  6. 从Commons CLI迁移到picocli

    最初于2002年发布的Apache Commons CLI可能是使用最广泛的Java命令行解析器,但是它的API显示了它的年龄. 寻找具有最少样板代码的现代方法的应用可能对picocli感兴趣. 为什 ...

  7. 使用 Apache Commons CLI 解析命令行参数示例

    很好的输入参数解析方法 ,转载记录下 转载在: https://www.cnblogs.com/onmyway20xx/p/7346709.html Apache Commons CLI 简介 Apa ...

  8. 时海君:apache第一讲-commons cli

    hello, 大家好,我是时海君,时海君就是我,一个自认为智商偏高,情商偏低的程序员.纵使程序虐我千百遍,我待IT如初恋.从今往后看破红尘,两耳不闻窗外事,一心只写圣贤代码.时海君这些年在java后台 ...

  9. Caused by: org.apache.commons.cli.MissingArgumentException: Missing argument f/h/s/v......

    今日在做一个基于Command CLI通过命令行控制参数的小模块,在输入-f参数后,报出这个错误: Caused by: org.apache.commons.cli.MissingArgumentE ...

  10. commons dbutils 的介绍与使用

    1.Commons dbutils是什么? commons-dbutils 是 Apache 组织提供的一个开源 JDBC 工具类库,对传统操作数据库的类进行二次封装,可以把结果集转化成List. 2 ...

最新文章

  1. teamcity plugin中读取js和css文件的方法
  2. 数据库防火墙——实现数据库的访问行为控制、危险操作阻断、可疑行为审计...
  3. Firefox 修改User Agent
  4. 解决:The application could not be installed: INSTALL_FAILED_SHARED_USER_INCOMPATIBLE
  5. 【人物】徐小平:既然做老大,你就得让兄弟们有肉吃
  6. 字符的用意_通达信某些字符的意义及用法
  7. python mongodb查询_Python MongoDB 查找
  8. 无线网络的基础及优化方案
  9. 使用alarm API实现灵活的延时操作
  10. 2018腾讯内部转岗面试题3——找出数组中比左边大比右边的小的元素
  11. IDEIDEA 如何搭建maven 安装、下载、配置A 如何搭建maven 安装、下载、配置
  12. 网络营销行业十大看了就想吐的“滥词”
  13. imagemagick gif制作
  14. iOS-百度地图之——POI检索失败BMK_SEARCH_PERMISSION_UNFINISHED
  15. iOS马甲包开发招式及规避4.3方法合集
  16. 组合数求解与(扩展)卢卡斯定理
  17. Error: spawn cmd ENOENT at Process.ChildProcess._handle.onexit
  18. 经纬张颖:给科研技术背景创始人的十条建议
  19. 一维卷积积分学习实例
  20. pyalgotrade量化回测框架简单试用

热门文章

  1. Vue项目启动时自动打开浏览器
  2. 【笔记 - linux基础入门 01】基本概念及操作
  3. 支付宝APP退款功能开发
  4. 利用python openpyxl库实现对多个excel工作簿的快速汇总
  5. mbit职业测试软件,MBTI职业性格测试(自动计算版)-
  6. 《财务共享服务》读书笔记
  7. Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.解决
  8. 二维线段树(线段树套线段树)
  9. 世界杯数据清单:真球迷看球必备,伪球迷速成指南(附数据amp;论文)
  10. 强制修改.ko文件中的内核版本号与内核对应