在Java中解析命令行参数的好方法是什么?
当前回答
Argparse4j是我发现的最好的。它模仿Python的argparse库,非常方便和强大。
其他回答
看看这些:
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.
我开发这个项目是因为我需要新的功能(选项,标志,子命令),并且可以在我的项目中以最简单的方式使用。
如果你熟悉gnu getopt,有一个Java端口:http://www.urbanophile.com/arenn/hacking/download.htm。
似乎有一些类是这样做的:
http://docs.sun.com/source/816-5618-10/netscape/ldap/util/GetOpt.html http://xml.apache.org/xalan-j/apidocs/org/apache/xalan/xsltc/cmdline/getopt/GetOpt.html
现在是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。欢迎反馈或提问。
是的。
我想你在寻找这样的东西: http://commons.apache.org/cli
Apache Commons CLI库提供了一个用于处理命令行接口的API。
推荐文章
- 使用Java重命名文件
- URL从Java中的类路径加载资源
- .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
- Hibernate中不同的保存方法之间有什么区别?
- 如何循环通过文件匹配通配符在批处理文件
- Java 8流和数组操作
- Java Regex捕获组
- Openssl不被视为内部或外部命令
- 如何添加自定义方法到Spring Data JPA
- 如何在Ubuntu中设置Java环境路径
- 无法执行dex:在Eclipse中超过GC开销限制
- 有人能解释一下JPA和Hibernate中的mappedBy吗?
- 是什么导致JNI调用变慢?
- Java中的&和&&有什么区别?
- 使用Java的Collections.singletonList()?