Common-cli的使用

2019-05-15  本文已影响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参数举例:

代码解析

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解析后的产物,保存了参数解析后对应的结果,并提供了多种操作参数结果的方法。

其属性为:

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

最后

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

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

上一篇 下一篇

猜你喜欢

热点阅读