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


当前回答

Argparse4j是我发现的最好的。它模仿Python的argparse库,非常方便和强大。

其他回答

Argparse4j是我发现的最好的。它模仿Python的argparse库,非常方便和强大。

我知道这里的大多数人会找到一千万个理由来解释他们为什么不喜欢我的方式,但没关系。我喜欢让事情变得简单,所以我只是使用'='将键和值分开,并将它们存储在一个HashMap中,就像这样:

Map<String, String> argsMap = new HashMap<>();
for (String arg: args) {
    String[] parts = arg.split("=");
    argsMap.put(parts[0], parts[1]);
} 

您可以始终维护一个包含您所期望的参数的列表,以帮助用户避免忘记参数或使用错误的参数……然而,如果你想要太多的功能,这个解决方案并不适合你。

看看这些:

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

我想向您展示我的实现:ReadyCLI

优点:

for lazy programmers: a very small number of classes to learn, just see the two small examples on the README in the repository and you are already at 90% of learning; just start coding your CLI/Parser without any other knowledge; ReadyCLI allows coding CLIs in the most natural way; it is designed with Developer Experience in mind; it largely uses the Builder design pattern and functional interfaces for Lambda Expressions, to allow a very quick coding; it supports Options, Flags and Sub-Commands; it allows to parse arguments from command-line and to build more complex and interactive CLIs; a CLI can be started on Standard I/O just as easily as on any other I/O interface, such as sockets; it gives great support for documentation of commands.

我开发这个项目是因为我需要新的功能(选项,标志,子命令),并且可以在我的项目中以最简单的方式使用。

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