commons-cli
是一个解析命令行输入的工具包。
能够让我们的Java程序实现类似如下的效果:
[root@upupfeng ~]# ls --help
Usage: ls [OPTION]... [FILE]...
-a, --all do not ignore entries starting with .
-A, --almost-all do not list implied . and ..
--author with -l, print the author of each file
-b, --escape print C-style escapes for nongraphic characters
--block-size=SIZE scale sizes by SIZE before printing them; e.g.,
支持通过- 参数名=..
来传参、支持-h
提示等。
在程序中设定命令行参数
解析输入参数
使用输入参数
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
public class CommonCliTest {
private static Options options = new Options();
public static void main(String[] args) throws Exception {
initCliArgs(args);
}
private static void initCliArgs(String[] args) throws Exception {
CommandLineParser parse = new PosixParser();
options.addOption("d", true, "the dir of file is required");
options.addOption("h", "help", false, "see usage");
CommandLine commandLine = null;
commandLine = parse.parse(options, args, false);
if (!commandLine.hasOption("d")) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("-d is required, please follow the below usage", options);
System.exit(0);
}
String dir = commandLine.getOptionValue("d");
System.out.println(dir);
}
}
说明:通过-d
传入参数,如果-d
没指定,则输出提示。
https://www.jianshu.com/p/c3ae61787a42
https://developer.ibm.com/zh/articles/j-lo-commonscli/
http://commons.apache.org/proper/commons-cli/