一、官方文档:http://commons.apache.org/proper/commons-cli/usage.html

二、举例说明:

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.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class MyMain {

    public static void main(String[] args) {
        
        Options options = new Options();
        OptionGroup group = new OptionGroup();
        group.addOption(
                Option.builder("d")
                .required()
                .hasArgs()
                .desc("scan directory")
                .longOpt("directory")
                .build()
                );
        group.addOption(
                Option.builder("t")
                .required()
                .hasArgs()
                .desc("target directory")
                .longOpt("template")
                .build()
                );
        group.setRequired(true);
        
        
        options.addOptionGroup(group)
            .addOption(
                    Option.builder("i")
                          .hasArgs()
                          .desc("ignore directory")
                          .longOpt("ignore")
                          .build()
                    )
            .addOption(
                    Option.builder("r")
                          .hasArgs()
                          .longOpt("result")
                          .desc("result directory")
                          .build()
                    );
        
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        
        try {
            cmd = parser.parse(options, args);
            if(cmd.hasOption("t")){
                String template = cmd.getOptionValue("template");
                System.out.println(template);
            }
        } catch (ParseException e) {
            helpU(options);
            return;
        }

    }
    
    public static void helpU(Options options){
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Java -jar MyMain.jar -* ",
                            "This is utility to scan copied files",
                            options, 
                            "ask support: send email to CPEG@calix.com", 
                            true);
        System.exit(1);
        
    }

}

 

转载于:https://www.cnblogs.com/lfdingye/p/7643977.html