用到的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. 信息:Could not publish server configuration for Tomcat v6.0 Server at localhost. Multiple Context

    需要把server.xml更正一下,去掉重复的context.或者把整个server文件夹都删掉,重新添加服务器.也可以在server窗口中删除server,再新添加一个server.

  2. Akka的Actor模型及使用实例

    本文的绝大部分内容转载自rerun.me这一blog,老外写的东西就是好啊. ACTORS介绍 Anyone who has done multithreading in the past won't ...

  3. UVa 10129 Play On Words【欧拉道路 并查集 】

    题意:给出n个单词,问这n个单词能否首尾接龙,即能否构成欧拉道路 按照紫书上的思路:用并查集来做,取每一个单词的第一个字母,和最后一个字母进行并查集的操作 但这道题目是欧拉道路(下面摘自http:// ...

  4. fiddler2抓包工具使用图文教程

    fiddler2抓包工具使用图文教程 三.fiddler实用功能使用说明: 1.fiddler捕获浏览器的会话: 能支持http代理的任意程序都能被fiddler捕获到,由于fiddler的运行机制就 ...

  5. 也说Autofac在MVC的简单实践:破解在Controller构造函数中的实例化 - winhu

    相信大家对Autofac并不陌生,很多人都在使用.本文只是介绍一下本人在使用时的一点想法总结. 在使用一个框架时,肯定要去它的官网查阅一下.autofac的官网给出了一些经典的使用案例.如注册容器: ...

  6. 硬盘结构介绍--mbr及分区

    硬盘刚买来使用时需要经过分区然后格式化才能够使用,硬盘经过分区后,分区软件便会写一个主引导扇区,这个扇区位于硬盘的 0 磁道 0 柱面第1扇区(即0区)(注意:该扇区为隐含扇区,0道0面的全部扇区均为 ...

  7. codeforces 691F Couple Cover 暴力

    分析:开一个300w的数组,统计,然后nlogn统计每个值在在序对第一个出现有多少种情况 时间复杂度:O(nlogn) n在3e6数量级 #include<cstdio> #include ...

  8. 简单把webdriver的find_element方法写成函数

    __author__ = 'jyd' from selenium.webdriver.common.by import By #driver webdriver实例化对象 #element 查询元素的 ...

  9. Int.Parse()、Convert.toInt32()和(int)区别

    通过网上的查询从而了解了Int.Parse().Convert.toInt32()和(int)区别. 一.定义上的差别 int类型表示一种整型,.NET Framework 类型为 System.In ...

  10. 【windows核心编程】使用远程线程注入DLL

    前言 该技术是指通过在[目标进程]中创建一个[远程线程]来达到注入的目的. 创建的[远程线程]函数为LoadLibrary, 线程函数的参数为DLL名字, 想要做的工作在DLL中编写.  示意图如下: ...