JAVA basics - use CommandLine to parse command line parameters

what is it

commons-cli is a powerful and open source command line parameter passing and parsing solution for receiving the args parameter of the MAIN method. Parameters can be defined by setting short options (that is, abbreviated option names), long options (that is, full letters), setting whether to carry option parameters (if false is specified, it means that this option has no parameters, that is, Boolean options) and description information options.
Official website: https://commons.apache.org/proper/commons-cli/index.html

Please read this blog post first:
Command line parameters under CENTOS: https://blog.csdn.net/goodjava2007/article/details/131083116

encoding steps

(1) Define parameters

Options options = new Options();

(2) Parsing parameters

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) Get parameters

String db = cmd.getOptionValue("d")

parameter style

serial number style type Parameter Description parser
1 POSIX style parameters Single-character POSIX-style arguments starting with "-", such as: tar -zxvf foo.tar.gz PosixParser
2 GNU style parameters GNU-style parameters with "- -" followed by option keywords, GNU style is compatible with POSIX style, such as: du - -human-readable - -max-depth=1 GnuParser
3 JAVA style parameter Parameters starting with "-D", such as: java -Datlas.log.file=import-hive.log -Dlog4j.configuration=atlas-hive-import-log4j.xml DefaultParser
4 short option parameter A single character parameter starting with "-", namely: dash + parameter name + space + parameter value (space can also be omitted), such as: import-hive.sh -dmallx -tmallx_order or import-hive.sh -d mallx -t mallx_order is fine DefaultParser / BasicParser
5 long option parameter Multiple character parameters starting with "-", such as: ant -projecthelp DefaultParser / BasicParser

Note: The above table describes the parameter style. As for whether a parameter is followed by the corresponding value of the parameter, it needs to be set in the code of the option.

how to use

① Dependency introduction
<dependency>
  <groupId>commons-cli</groupId>
  <artifactId>commons-cli</artifactId>
  <version>1.4</version>
</dependency>
② sample code
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;
    }
}
③ Example test

Set parameters in IDEA as follows:

"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

insert image description here

④ Execution result
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
⑤ Official example

COMMONS CLI official example: https://commons.apache.org/proper/commons-cli/usage.html

Guess you like

Origin blog.csdn.net/goodjava2007/article/details/131068888