美文网首页
Common-cli的使用

Common-cli的使用

作者: 新签名 | 来源:发表于2019-05-15 17:53 被阅读0次

Common-cli的使用

它能让你的jar包支持这样传参数以及help提示

Missing required options: h, u, p, s, d
usage: scp -help
 -d,--dst_path <arg>   the dstPath of remote
 -h,--host <ipv4 or ipv6>     the host of remote server
 -help                 usage help
 -P,--port <arg>       the port of remote server
 -p,--password <arg>   the password of remote server
 -s,--src_path <arg>   the srcPath of local
 -u,--user <arg>       the user of remote server

简介

common-cli组件是一个解析命令参数的jar包,它能解析gnu风格参数、posix风格参数。精简而又强大,大小仅由二十多个class组成,maven地址如下:

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

例子

举个scp常用参数的例子说明详细说明下用法,以及参数的各个属性:

import org.apache.commons.cli.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * description
 *
 * @author zk
 * @since 2019/5/15
 */
public class ScpCmdTest {
    private static Options OPTIONS = new Options();
    private static CommandLine commandLine;
    private static String HELP_STRING = null;

    public static void main(String[] args) {
        initCliArgs(args);
    }

    /**
     * init args
     *
     * @param args args
     */
    private static void initCliArgs(String[] args) {
        CommandLineParser commandLineParser = new DefaultParser();
        // help
        OPTIONS.addOption("help","usage help");
        // host
        OPTIONS.addOption(Option.builder("h").argName("ipv4 or ipv6").required().hasArg(true).longOpt("host").type(String.class).desc("the host of remote server").build());
        // port
        OPTIONS.addOption(Option.builder("P").hasArg(true).longOpt("port").type(Short.TYPE).desc("the port of remote server").build());
        // user
        OPTIONS.addOption(Option.builder("u").required().hasArg(true).longOpt("user").type(String.class).desc("the user of remote server").build());
        // password
        OPTIONS.addOption(Option.builder("p").required().hasArg(true).longOpt("password").type(String.class).desc("the password of remote server").build());
        // srcPath
        OPTIONS.addOption(Option.builder("s").required().hasArg(true).longOpt("src_path").type(String.class).desc("the srcPath of local").build());
        // dstPath
        OPTIONS.addOption(Option.builder("d").required().hasArg(true).longOpt("dst_path").type(String.class).desc("the dstPath of remote").build());
        try {
            commandLine = commandLineParser.parse(OPTIONS, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage() + "\n" + getHelpString());
            System.exit(0);
        }

    }

    /**
     * get string of help usage
     *
     * @return help string
     */
    private static String getHelpString() {
        if (HELP_STRING == null) {
            HelpFormatter helpFormatter = new HelpFormatter();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PrintWriter printWriter = new PrintWriter(byteArrayOutputStream);
            helpFormatter.printHelp(printWriter, HelpFormatter.DEFAULT_WIDTH, "scp -help", null,
                    OPTIONS, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null);
            printWriter.flush();
            HELP_STRING = new String(byteArrayOutputStream.toByteArray());
            printWriter.close();
        }
        return HELP_STRING;
    }
}

简单运行示例:

Missing required options: h, u, p, s, d
usage: scp -help
 -d,--dst_path <arg>   the dstPath of remote
 -h,--host <ipv4 or ipv6>     the host of remote server
 -help                 usage help
 -P,--port <arg>       the port of remote server
 -p,--password <arg>   the password of remote server
 -s,--src_path <arg>   the srcPath of local
 -u,--user <arg>       the user of remote server

host参数举例:

  • 设置了h短选项和host长选项,意味着入参使用-h 127.0.0.1-host 127.0.0.1方式传入,都能成功赋值。
  • 设置了hasArg(true)属性,说明它是有值选项。
  • 设置了required(),该参数的值必填。
  • 配置argName("ipv4 or ipv6")是对参数值的说明,若不填就会像其他参数一样会提示<arg>
  • 设置type(String.class),说明该参数的值应该为String类型
  • 设置desc是对该参数的详细描述,如对host的参数说明:the host of remote server

代码解析

Option

该类是描述具体参数的基础类,它有以下这些基础属性

属性名 类型 描述
argName String 参数值说明
description String 参数描述
opt String 短选项名;比如:-p=22,p就是该短选项名
longOpt String 长选项类型;比如:-p=22 --port=22,port就是该长选项名
numberOfArgs int 参数个数
optionalArg boolean 是否可选
required boolean 是否必填
type Class 参数类型
valuesep char 值分隔符;采用java参数风格解析时用来分支值,如:-Dkey=value。

valuesep属性详见org.apache.commons.cli#Builder#valueSeparator

Option可以通过new生成,也可以通过Option.builder()构造生成。

CommandLineParser

CommandLineParser继承类如下:

image

GnuParserPosixParser解析器分别代表gnuParser参数风格和posixParser参数风格,不过在1.3版本中连同父类Parser都被废除并统一重构成了DefaultParser,可能觉得不太常用,仅留下了这句话the two-pass parsing with the flatten method is not enough flexible to handle complex cases

posix风格参数以-开头;gnu风格参数兼容posix并推荐以--开头,以及还有一些其他奇葩的操作。知乎上这篇文章下的评论还算解析的可以。

common-cli-1.3之后推荐使用DefaultParser,它废弃了gnu的奇葩操作,仅提供--key=value-key=value-Dkey=value类型的参数和properties参数的解析,可能觉得保留常用的就可以了。

CommandLine

CommdLine类是经过parser解析后的产物,保存了参数解析后对应的结果,并提供了多种操作参数结果的方法。

其属性为:

  • List<String> args : 原始参数
  • List<Option> options : 解析后的option

方法均为操作者两种的工具方法。

最后

该组件是属于不常用,但是用时非常nice的工具,所以理解后精华就在demo上了。

另外如果对这个java ftp工具感兴趣,请移步这里(免密scp)

相关文章

  • Common-cli的使用

    Common-cli的使用 它能让你的jar包支持这样传参数以及help提示 简介 common-cli组件是一个...

  • iconfont的使用(下载使用)

    1、下载文件 2、在生命周期中引入项目 beforeCreate () { var domModule = ...

  • Gson的使用--使用注解

    Gson为了简化序列化和反序列化的过程,提供了很多注解,这些注解大致分为三类,我们一一的介绍一下。 自定义字段的名...

  • 记录使用iframe的使用

    默认记录一下----可以说 这是我第一次使用iframe 之前都没有使用过; 使用方式: 自己开发就用了这几个属...

  • with的使用

    下面例子可以具体说明with如何工作: 运行代码,输出如下

  • this的使用

    什么是this? this是一个关键字,这个关键字总是返回一个对象;简单说,就是返回属性或方法“当前”所在的对象。...

  • this的使用

    JS中this调用有几种情况 一:纯粹的函数调用 这是函数的最通常用法,属于全局性调用,因此this就代表全局对象...

  • ==的使用

    积累日常遇到的编码规范,良好的编码习惯,持续更新。。。 日常使用==用于判断的时候,习惯性将比较值写前面,变量写后...

  • this的使用

    1.默认绑定,就是函数立即执行。 函数立即执行就是指向window,但是如果是node环境,就是指向全局conso...

  • %in% 的使用

    写在前面:From 生信技能书向量难点之一:%in% 难点 (1)== 与 %in% 的区别== 强调位置,x和对...

网友评论

      本文标题:Common-cli的使用

      本文链接:https://www.haomeiwen.com/subject/pssmaqtx.html