CommonsCli 是 Apache Commons 库中的一个组件,它提供了一种方便的方式来解析命令行参数。如果你需要解析一个可以多次出现并具有灵活数量的值的选项,你可以使用 Option
类的 setArgs
方法来指定该选项可以接受的参数数量,然后通过 CommandLine
对象来获取这些参数的值。
以下是一个简单的示例代码,展示了如何使用 CommonsCli 解析一个名为 -f
或 --files
的选项,该选项可以接受多个文件路径作为参数:
import org.apache.commons.cli.*;
public class CliExample {
public static void main(String[] args) {
// 创建 Options 对象
Options options = new Options();
// 添加 -f/--files 选项,允许有多个参数
Option files = Option.builder("f")
.longOpt("files")
.hasArgs() // 表示该选项可以接受参数
.argName("FILE") // 参数名称
.desc("Specify one or more files") // 描述
.build();
options.addOption(files);
// 创建命令行解析器
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
// 解析命令行参数
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
return;
}
// 获取 -f/--files 选项的所有参数值
if (cmd.hasOption("f")) {
String[] fileNames = cmd.getOptionValues("f");
for (String fileName : fileNames) {
System.out.println("File: " + fileName);
}
}
}
}
在这个例子中,-f
或 --files
选项可以接受任意数量的文件路径作为参数。当你运行这个程序并提供 -f
选项时,你可以像这样传递多个文件路径:
java CliExample -f file1.txt file2.txt file3.txt
程序会解析这些参数并打印出每个文件的路径。
Option
类代表命令行中的一个选项,它可以有自己的简写形式、完整形式、描述以及参数。ParseException
并给出有用的错误信息。通过上述代码和解释,你应该能够理解如何使用 CommonsCli 解析具有多个值的命令行选项,并且知道如何处理可能出现的问题。
领取专属 10元无门槛券
手把手带您无忧上云