commons.cli命令行交互

public static void main(String[] args) throws ParseException {
    String[] p = {"-h"};
    parse(p, "test");
}

public static void parse(String[] args, String cmdName) throws ParseException {

    Options options = getOptions();
    // 解析
    // 1.3.1中已经弃用针对不同格式入参对应的解析器
    // CommandLineParser parser = new PosixParser();
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = parser.parse(options, args);

    if (commandLine.hasOption('h')) {
        HelpFormatter helpFormatter = new HelpFormatter();
        int width = 110;
        String cmdLineSyntax = cmdName;
        String header = "title";
        String footer = "bottom content";
        boolean autoUsage = true;
        // 有多个重载方法
        helpFormatter.printHelp(width, cmdLineSyntax, header, options, footer, autoUsage);
        return;
    }

}

public static Options getOptions() {

    Options options = new Options();
    // String opt         :短命令
    // String longOpt     :长命令
    // boolean hasArg     :true:有参数;false:无参数
    // String description :描述
    Option opt = new Option("h", "help", false, "Print help");
    // true:必须;false:非必须
    // 必填但没填,会抛异常MissingOptionException
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("i", "ips", true, "ip list, eg: 127.0.0.1;127.0.0.2");
    // 必填但没填,会抛异常MissingOptionException
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("lf", "loadFile", true, "load file form your file path");
    opt.setRequired(false);
    options.addOption(opt);

    return options;
}

你可能感兴趣的:(java命令行交互,java实战案例)