commons-cli:命令行参数解析库

commons-CLI.png

背景

Apache Commons CLI包用于解析命令行参数,并可以打印命令行help信息。

支持以下类型:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)

在阅读flume源码时,发现它的命令行解析用的就是commons-cli。

实操

    <dependency>
        <groupId>commons-cli</groupId>
        <artifactId>commons-cli</artifactId>
        <version>1.4</version>
    </dependency>
package com.example.note;

import java.util.Properties;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CommonCliTest {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();

        // 有两种方式 -n 或者 --name
        Option option = new Option("n", "name", true, "the name of this agent");
        option.setRequired(true);// 必填
        options.addOption(option);

        option = new Option("f", "conf-file", true, "specify a config file (required if -z missing)");
        option.setRequired(false);// 选填
        options.addOption(option);

        option = new Option(null, "no-reload-conf", false, "do not reload config file if changed");
        options.addOption(option);

        option = new Option("h", "help", false, "display help text");
        options.addOption(option);

        //java -Dcom.example.db=order
        option = Option.builder("D").argName("property=name").hasArgs().valueSeparator().desc("use value for a property").longOpt(null).build();
        options.addOption(option);

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

        if (commandLine.hasOption('h')) {
            // 打印help信息
            new HelpFormatter().printHelp("flume-ng agent", options, true);
            return;
        }

        // 获取命令行参数
        String agentName = commandLine.getOptionValue('n');
        System.out.println(agentName);
        
        Properties properties = commandLine.getOptionProperties("D");
        System.out.println(properties);
    }
}
输入 flume-ng agent -n game -f /app/flume/conf/game.conf 
可以获得name为game,file为/app/flume/conf/game.conf

参考

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容