Skip to content

Java 解析 args 参数

🏷️ Java

这里是使用 Commons-CLI 的示例,原文中还有使用 Args4JJCommander 的示例。

java
package com.ocotopus.octpusapiservices;

import org.apache.commons.cli.*;

import java.util.Date;

/**
 * Created by liujiajia on 2017/2/16.
 */
public class ArgsTest {
    public static void main(String[] args) {
        args = new String[]{"-t", "rensanning", "-f", "c:/aa.txt", "-b", "-s10", "-Dkey1=value1", "-Dkey2=value2" };
        try {
            // create Options object
            Options options = new Options();
            options.addOption(new Option("t", "text", true, "use given information(String)"));
            options.addOption(new Option("b", false, "display current time(boolean)"));
            options.addOption(new Option("s", "size", true, "use given size(Integer)"));
            options.addOption(new Option("f", "file", true, "use given file(File)"));

            @SuppressWarnings("static-access")
            Option property = OptionBuilder.withArgName("property=value")
                    .hasArgs(2)
                    .withValueSeparator()
                    .withDescription("use value for given property(property=value)")
                    .create("D");
            property.setRequired(true);
            options.addOption(property);

            // print usage
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp( "AntOptsCommonsCLI", options );
            System.out.println();

            // create the command line parser
            CommandLineParser parser = new PosixParser();
            CommandLine cmd = parser.parse(options, args);

            // check the options have been set correctly
            System.out.println(cmd.getOptionValue("t"));
            System.out.println(cmd.getOptionValue("f"));
            if (cmd.hasOption("b")) {
                System.out.println(new Date());
            }
            System.out.println(cmd.getOptionValue( "s" ));
            System.out.println(cmd.getOptionProperties("D").getProperty("key1") );
            System.out.println(cmd.getOptionProperties("D").getProperty("key2") );

        } catch (Exception ex) {
            System.out.println( "Unexpected exception:" + ex.getMessage() );
        }
    }
}

执行结果:

bash
usage: AntOptsCommonsCLI
 -b                    display current time(boolean)
 -D    use value for given property(property=value)
 -f,--file        use given file(File)
 -s,--size        use given size(Integer)
 -t,--text        use given information(String)

rensanning
c:/aa.txt
Thu Feb 16 14:14:51 CST 2017
10
value1
value2

Process finished with exit code 0

原文:Java 命令行选项解析之 Commons-CLI & Args4J & JCommander