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


当前回答

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

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

也许这些

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

我想向您展示我的实现: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.

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

正如前面提到的一个评论(https://github.com/pcj/google-options)是一个很好的开始。

我想补充的一点是:

1)如果您遇到一些解析器反射错误,请尝试使用更新版本的guava。在我的例子中:

maven_jar(
    name = "com_google_guava_guava",
    artifact = "com.google.guava:guava:19.0",
    server = "maven2_server",
)

maven_jar(
    name = "com_github_pcj_google_options",
    artifact = "com.github.pcj:google-options:jar:1.0.0",
    server = "maven2_server",
)

maven_server(
    name = "maven2_server",
    url = "http://central.maven.org/maven2/",
)

2)当运行命令行时:

bazel run path/to/your:project -- --var1 something --var2 something -v something

3)当你需要使用帮助时,只需输入:

bazel run path/to/your:project -- --help