用到的jar包

        <dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.3.1</version>
</dependency>

Option 的格式

Option(String opt, String longOpt, boolean hasArg, String description)
选项名,选项全称,是否有参数(如果true时没有参数会抛异常),描述
例如:
new Option("h","help",false,"print help");

Option 合法性校验

OptionValidator.class
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.apache.commons.cli; /**
* Validates an Option string.
*
* @version $Id: OptionValidator.java 1544819 2013-11-23 15:34:31Z tn $
* @since 1.1
*/
final class OptionValidator
{
/**
* Validates whether <code>opt</code> is a permissible Option
* shortOpt. The rules that specify if the <code>opt</code>
* is valid are:
*
* <ul>
* <li>a single character <code>opt</code> that is either
* ' '(special case), '?', '@' or a letter</li>
* <li>a multi character <code>opt</code> that only contains
* letters.</li>
* </ul>
* <p>
* In case {@code opt} is {@code null} no further validation is performed.
*
* @param opt The option string to validate, may be null
* @throws IllegalArgumentException if the Option is not valid.
*/
static void validateOption(String opt) throws IllegalArgumentException
{
// if opt is NULL do not check further
if (opt == null)
{
return;
} // handle the single character opt
if (opt.length() == 1)
{
char ch = opt.charAt(0); if (!isValidOpt(ch))
{
throw new IllegalArgumentException("Illegal option name '" + ch + "'");
}
} // handle the multi character opt
else
{
for (char ch : opt.toCharArray())
{
if (!isValidChar(ch))
{
throw new IllegalArgumentException("The option '" + opt + "' contains an illegal "
+ "character : '" + ch + "'");
}
}
}
} /**
* Returns whether the specified character is a valid Option.
*
* @param c the option to validate
* @return true if <code>c</code> is a letter, '?' or '@', otherwise false.
*/
private static boolean isValidOpt(char c)
{
return isValidChar(c) || c == '?' || c == '@';
} /**
* Returns whether the specified character is a valid character.
*
* @param c the character to validate
* @return true if <code>c</code> is a letter.
*/
private static boolean isValidChar(char c)
{
return Character.isJavaIdentifierPart(c);
}
}

常见异常

  • org.apache.commons.cli.UnrecognizedOptionException
  • org.apache.commons.cli.MissingOptionException
  • org.apache.commons.cli.MissingArgumentException

CommandLine commandLine = parser.parse(options, args);

如果args开启某option,但options中不包含时,未识别选项

如果args开启某option,该option已设置为包含参数,但args 中没有该option参数时,丢失参数

如果某option已设置为必须,但args中未开启该option是,丢失选项

小样

package cli;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException; public class TestCommandline {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option opt = new Option("n", "namesrvAddr", true,
"Name server address list, eg: 192.168.0.1:9876;192.168.0.2:9876");
opt.setRequired(false);
options.addOption(opt); CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(options, args); String optNmae = "n";
if (commandLine.hasOption(optNmae)) {
System.out.println(commandLine.getOptionValue(optNmae));
for (String s : commandLine.getOptionValues(optNmae)) {
System.out.print(s+" ");
}
}
}
}

入参:

-n 192.168.0.1:9876 -n 192.168.0.2:9876

结果:

192.168.0.1:9876
192.168.0.1:9876 192.168.0.2:9876

小结

必须由『-』开启选项,短横后面需合法,由空格(不限个数)区分选项和参数。

一个选项只能跟一个参数。

选项参数对之外的自动忽略。

两个相同的选项参数由左至右依次被设置到参数数组中。

CommandLine 和 Options的更多相关文章

  1. C# 借助CommandLine 写命令行工具 在数据库中创建job

    首先需要用到  CommandLine.dll 提供两个下载链接,云盘是我自己上传的,也就是我在用的 http://commandline.codeplex.com/ https://pan.baid ...

  2. HTTrack 网站备份工具

    HTTrack可以克隆指定网站-把整个网站下载到本地.可以用在离线浏览上,免费的噢! 强大的Httrack类似于搜索引擎的爬虫,也可以用来收集信息.记得之前写过篇http://www.cnblogs. ...

  3. GO语言的开源库

    Indexes and search engines These sites provide indexes and search engines for Go packages: godoc.org ...

  4. Samza在YARN上的启动过程 =》 之一

    运行脚本,提交job 往YARN提交Samza job要使用run-job.sh这个脚本. samza-example/target/bin/run-job.sh  --config-factory= ...

  5. Go语言(golang)开源项目大全

    转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析 ...

  6. [转]Go语言(golang)开源项目大全

    内容目录 Astronomy 构建工具 缓存 云计算 命令行选项解析器 命令行工具 压缩 配置文件解析器 控制台用户界面 加密 数据处理 数据结构 数据库和存储 开发工具 分布式/网格计算 文档 编辑 ...

  7. Docker 核心技术之容器

    什么是容器 容器(Container) 容器是一种轻量级.可移植.并将应用程序进行的打包的技术,使应用程序可以在几乎任何地方以相同的方式运行 Docker将镜像文件运行起来后,产生的对象就是容器.容器 ...

  8. docker不能上传镜像到自己网站的仓库

    错误提示如下: WARNING! Using --password via the CLI is insecure. Use --password-stdin. Error response from ...

  9. [转帖]Docker的daemon.json的作用

    Docker(十六)-Docker的daemon.json的作用 https://www.cnblogs.com/zhuochong/p/10070434.html jfrog 培训的时候 说过这个地 ...

随机推荐

  1. bzoj4044

    这题简直了………… 首先根据操作可知,我们肯定是先造出某个偶数长度的回文串,然后添加若干字符得到设回文串长为len[x] 则ans=min(n-len[x]+f[x]); 那么问题就是制造这个串的回文 ...

  2. BZOJ2298: [HAOI2011]problem a

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2298 题解:刚开始思考的方向错了...一直在想LIS什么的,又发现不合法的情况不好判断,真是个 ...

  3. Android开发之WebService介绍

    经常有网友问:“在Android平台如何调用WebService”?经过沟通我发现,甚至有些朋友连什么是WebSerivce都不知道就在问怎么使用,更别说和WebService有关的SOAP.WSDL ...

  4. Java知识点:琐碎知识点(3)

    零碎 switch(x),x只可以是enum或byte.short.char.int. 枚举在switch-case语句作为标签时必须是枚举常量的非限定名称,否则Compile Error. Enum ...

  5. ios tweak之binary not signed (use ldid -S)问题解决

    参考tweak教程写了个简单的tweak,无奈完全无效果,摸索了好长时间才找到方法: 打开terminal ssh root@192.168.1.100 vim /var/log/syslog 找到如 ...

  6. 【解决方案】jquery live的change事件在IE下失效

    $("#spanChildSec select").live("change", function () {              //处理内容       ...

  7. poj 1787 Charlie's Change

    // 题意 给定一个数p,要求用四种币值为1,5,10,25的硬币拼成p,并且硬币数要最多,如果无解输出"Charlie cannot buy coffee.",1<=p&l ...

  8. Blog CSS

    你好 print("你好.") haode

  9. 【打表】HDOJ-2089-不要62

    [题目链接:HDOJ-2089] 多组测试数据,所以可以先算出符合条件的所有数保存数组中,输入时则直接遍历数组. #include<iostream> #include<cstrin ...

  10. Oracle 课程七之分析和动态采样

    课程目标 完成本课程的学习后,您应该能够: •引子—统计信息的作用 •如何收集统计信息 •系统统计信息 •对象统计信息—表.字段.索引统计信息 •动态采样   统计信息的作用 Optimizer st ...