How do I parse command line arguments in Java?

前端 未结 19 1686
终归单人心
终归单人心 2020-11-22 00:16

What is a good way of parsing command line arguments in Java?

19条回答
  •  鱼传尺愫
    2020-11-22 00:43

    It is 2020, time to do better than Commons CLI... :-)

    Should you build your own Java command line parser, or use a library?

    Many small utility-like applications probably roll their own command line parsing to avoid the additional external dependency. picocli may be an interesting alternative.

    Picocli is a modern library and framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It lives in 1 source file so apps can include it as source to avoid adding a dependency.

    It supports colors, autocompletion, subcommands, and more. Written in Java, usable from Groovy, Kotlin, Scala, etc.

    Features:

    • Annotation based: declarative, avoids duplication and expresses programmer intent
    • Convenient: parse user input and run your business logic with one line of code
    • Strongly typed everything - command line options as well as positional parameters
    • POSIX clustered short options ( -xvfInputFile as well as -x -v -f InputFile)
    • Fine-grained control: an arity model that allows a minimum, maximum and variable number of parameters, e.g, "1..*", "3..5"
    • Subcommands (can be nested to arbitrary depth)
    • Feature-rich: composable arg groups, splitting quoted args, repeatable subcommands, and many more
    • User-friendly: usage help message uses colors to contrast important elements like option names from the rest of the usage help to reduce the cognitive load on the user
    • Distribute your app as a GraalVM native image
    • Works with Java 5 and higher
    • Extensive and meticulous documentation

    The usage help message is easy to customize with annotations (without programming). For example:

    (source)

    I couldn't resist adding one more screenshot to show what usage help messages are possible. Usage help is the face of your application, so be creative and have fun!

    Disclaimer: I created picocli. Feedback or questions very welcome.

提交回复
热议问题