在Java中解析命令行参数的好方法是什么?
当前回答
我一直试图维护一个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彩色使用帮助和自动完成
其他回答
我知道这里的大多数人会找到一千万个理由来解释他们为什么不喜欢我的方式,但没关系。我喜欢让事情变得简单,所以我只是使用'='将键和值分开,并将它们存储在一个HashMap中,就像这样:
Map<String, String> argsMap = new HashMap<>();
for (String arg: args) {
String[] parts = arg.split("=");
argsMap.put(parts[0], parts[1]);
}
您可以始终维护一个包含您所期望的参数的列表,以帮助用户避免忘记参数或使用错误的参数……然而,如果你想要太多的功能,这个解决方案并不适合你。
如果您想要一些轻量级的(jar大小~ 20 kb)并且使用简单的东西,您可以尝试参数解析器。它可以在大多数用例中使用,支持在参数中指定数组,并且不依赖于任何其他库。它适用于Java 1.5或更高版本。下面摘录了一个如何使用它的例子:
public static void main(String[] args) {
String usage = "--day|-d day --mon|-m month [--year|-y year][--dir|-ds directoriesToSearch]";
ArgumentParser argParser = new ArgumentParser(usage, InputData.class);
InputData inputData = (InputData) argParser.parse(args);
showData(inputData);
new StatsGenerator().generateStats(inputData);
}
更多的例子可以在这里找到
航空公司@ Github看起来不错。它基于注释,并试图模拟Git命令行结构。
现在是2022年,是时候比Commons CLI做得更好了……: -)
您应该构建自己的Java命令行解析器,还是使用库?
许多类似于实用程序的小型应用程序可能会滚动自己的命令行解析,以避免额外的外部依赖。Picocli可能是一个有趣的替代方案。
Picocli是一个现代化的库和框架,用于轻松构建强大的、用户友好的、支持graalvm的命令行应用程序。它存在于一个源文件中,所以应用程序可以将它作为源文件来包含,以避免添加依赖项。
它支持颜色、自动补全、子命令等等。用Java编写,可从Groovy、Kotlin、Scala等中使用。
特点:
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 (<command> -xvfInputFile as well as <command> -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
使用帮助消息很容易使用注释进行定制(无需编程)。例如:
(源)
我忍不住又加了一张截图来展示使用帮助信息的可能性。使用帮助是应用程序的门面,所以要有创意,玩得开心!
声明:我创建了picocli。欢迎反馈或提问。
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 8 foreach循环移动到下一项
- 如何从终端/命令行调用VS代码编辑器
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder