在Java中解析命令行参数的好方法是什么?


当前回答

看看Commons CLI项目,里面有很多好东西。

其他回答

看看这些:

http://commons.apache.org/cli/ http://www.martiansoftware.com/jsap/

或者自己卷:

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html


例如,这是你如何使用common -cli来解析2个字符串参数:

import org.apache.commons.cli.*;

public class Main {


    public static void main(String[] args) throws Exception {

        Options options = new Options();

        Option input = new Option("i", "input", true, "input file path");
        input.setRequired(true);
        options.addOption(input);

        Option output = new Option("o", "output", true, "output file");
        output.setRequired(true);
        options.addOption(output);

        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        CommandLine cmd = null;//not a good practice, it serves it purpose 

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            formatter.printHelp("utility-name", options);

            System.exit(1);
        }

        String inputFilePath = cmd.getOptionValue("input");
        String outputFilePath = cmd.getOptionValue("output");

        System.out.println(inputFilePath);
        System.out.println(outputFilePath);

    }

}

命令行用法:

$> java -jar target/my-utility.jar -i asd                                                                                       
Missing required option: o

usage: utility-name
 -i,--input <arg>    input file path
 -o,--output <arg>   output file

看看Commons CLI项目,里面有很多好东西。

For Spring users, we should mention also https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/SimpleCommandLinePropertySource.html and his twin brother https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/JOptCommandLinePropertySource.html (JOpt implementation of the same functionality). The advantage in Spring is that you can directly bind the command line arguments to attributes, there is an example here https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html

我一直试图维护一个Java CLI解析器列表。

航空公司 Active Fork: https://github.com/rvesse/airline argparse4j argparse args4j clajr cli-parser CmdLn 命令行 DocOpt.java 海豚getopt DPML CLI (Jakarta Commons CLI2分支) 马蒂亚斯·劳克斯博士 Jakarta Commons CLI jargo jargp jargs java-getopt jbock JCLAP jcmdline jcommander jcommando Jewelcli(作者:我) JOpt简单 jsap naturalcli Object Mentor CLI文章(关于重构和TDD的更多内容) parse-cmd ritopt 罗普 TE-Code命令 picocli有ANSI彩色使用帮助和自动完成

也许这些

JArgs命令行选项解析 这个小项目为Java程序员提供了一个方便、紧凑、预打包和全面文档化的命令行选项解析器套件。最初,提供了与gnu风格的“getopt”兼容的解析。 ritopt, Java的终极选项解析器——尽管已经预先提出了几个命令行选项标准,ritopt仍然遵循opt包中规定的约定。