JAVA基础 - 使用CommandLine解析命令行参数

它是什么

commons-cli 是一个强大而的开源的命令行参数传递与解析的解决方案,用于接收MAIN方法的args参数。可以通过设置短选项(即选项名简写)、长选项(即全写)、设置是否需要携带选项参数(指定为 false 时,表示此选项不带参数,即为布尔选项)和描述信息来定义参数选项。
官网:https://commons.apache.org/proper/commons-cli/index.html

请先阅读该博文:
CENTOS下的命令行参数:https://blog.csdn.net/goodjava2007/article/details/131083116

编码步骤

(1)定义参数

Options options = new Options();

(2)解析参数

CommandLine cmd = new BasicParser().parse(options, args);
// 或者
CommandLine cmd = new DefaultParser().parse(options, args);
// 或者
CommandLine cmd = new PosixParser().parse(options, args);
// 或者
CommandLine cmd = new GnuParser().parse(options, args);

(3)获取参数

String db = cmd.getOptionValue("d")

参数风格

序号风格类型参数描述解析器
1POSIX风格参数以“-”开头的单个字符的POSIX风格的参数,如:tar -zxvf foo.tar.gzPosixParser
2GNU风格参数以“- -”后接选项关键字的GNU风格的参数,GNU风格兼容POSIX风格,如:du - -human-readable - -max-depth=1GnuParser
3JAVA风格参数以“-D”开头的参数,如:java -Datlas.log.file=import-hive.log -Dlog4j.configuration=atlas-hive-import-log4j.xmlDefaultParser
4短选项参数以“-”开头的单个字符参数,即:横杠+参数名+空格+参数值(空格也可以不带),如:import-hive.sh -dmallx -tmallx_order 或者 import-hive.sh -d mallx -t mallx_order 都可以DefaultParser / BasicParser
5长选项参数以“-”开头的多个字符参数,如:ant -projecthelpDefaultParser / BasicParser

注:以上表格说明的是参数风格,至于某个参数后面是否带参数对应的值,需要在选项的代码中进行设置。

如何使用

① 依赖引入
<dependency>
  <groupId>commons-cli</groupId>
  <artifactId>commons-cli</artifactId>
  <version>1.4</version>
</dependency>
② 示例代码
public class MyCommandLine {

    public static void main(String[] args) {
        MyCommandLine mcl = new MyCommandLine();
        mcl.defaultParser(args);
    }


    private void defaultParser(String[] args) {
        Options options = new Options();
        try {

            // 1.1 构造参数
            options.addOption("help", "如何使用mcl指令");
            options.addOption("d", "database", true, "指定数据库名");
            options.addOption("t", "table", true, "指定表名");
            options.addOption("s", "size", true, "指定文件的大小");
            options.addOption("f", "filename", true, "指定文件的全路径名");
            options.addOption("failOnError", false, "指定出现错误是是否停止");

            Option property = Option.builder("D")
                    .argName("property=value")
                    .hasArgs()
                    .valueSeparator('=')
                    .desc("指定KEY=VALUE形式的参数")
                    .build();

            options.addOption(property);


            // 1.2 解析
            CommandLine cmd = new DefaultParser().parse(options, args);

            // 1.3 取值
            boolean failOnError = cmd.hasOption("failOnError");
            String db = cmd.getOptionValue("d");       // 数据库
            String table = cmd.getOptionValue("t");    // 表
            String size = cmd.getOptionValue("s");     // 表大小
            String file = cmd.getOptionValue("f");     // 文件
            String log = cmd.getOptionProperties("D").getProperty("atlas.log");
            // 以下仅仅用于测试
            // 输出USAGE
            System.out.println(getHelp(options));
            // 输出参数
            System.out.println(String.format("The db is: %s, table is: %s, size is : %s, file is: %s, log is %s", db, table, size, file, log));
        } catch (Exception e) {

        } finally {

        }
    }

    private String getHelp(Options options) {
        HelpFormatter helper = new HelpFormatter();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PrintWriter printWriter = new PrintWriter(byteArrayOutputStream);
        helper.printHelp(printWriter, HelpFormatter.DEFAULT_WIDTH, "mcl -help", null,
                options, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null);
        printWriter.flush();
        String help = new String(byteArrayOutputStream.toByteArray());
        printWriter.close();
        return help;
    }
}
③ 示例测试

在IDEA中进行参数设置,如下:

"Program arguments" 输入框中如下设置:
-d mallx -tmallx_order -s1000 -Datlas.log=import-hive.log -f D:\02-工作空间\06-代码空间\04-gitee\rills-atlas-2.1.0-rc3\README.txt

在这里插入图片描述

④ 执行结果
usage: mcl -help
 -d,--database <arg>   指定数据库名
 -D <property=value>   指定KEY=VALUE形式的参数
 -f,--filename <arg>   指定文件的全路径名
 -failOnError          指定出现错误是是否停止
 -help                 如何使用mcl指令
 -s,--size <arg>       指定文件的大小
 -t,--table <arg>      指定表名

The db is: mallx, table is: mallx_order, size is : 1000, file is: D:\02-工作空间\06-代码空间\04-gitee\rills-atlas-2.1.0-rc3\README.txt, log is import-hive.log
⑤ 官方示例

COMMONS CLI 官方示例:https://commons.apache.org/proper/commons-cli/usage.html

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cloneme01

谢谢您的支持与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值