要解决Apache Commons Cli错误地接受重复选项的问题,您可以使用OptionBuilder
类中的hasArg
方法来指示选项是否接受参数,并使用OptionBuilder
类中的create
方法创建选项。以下是一个示例代码:
import org.apache.commons.cli.*;
public class CliExample {
public static void main(String[] args) {
Options options = new Options();
Option option = OptionBuilder.withLongOpt("input")
.withDescription("input file")
.hasArg()
.create("i");
options.addOption(option);
CommandLineParser parser = new DefaultParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("i")) {
String inputFilePath = cmd.getOptionValue("i");
System.out.println("Input file path: " + inputFilePath);
} else {
System.out.println("Input file option is missing");
}
} catch (ParseException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
在上面的示例中,我们使用OptionBuilder
类创建了一个名为"input"的选项,它的短选项是"i"。通过调用hasArg
方法,我们指示该选项需要一个参数。然后,我们将该选项添加到Options
对象中。
然后,我们使用DefaultParser
类将命令行参数解析为CommandLine
对象。通过调用hasOption
方法,我们检查命令行中是否存在"i"选项。如果存在,我们可以通过调用getOptionValue
方法获取该选项的值。
请注意,OptionBuilder
类在Apache Commons CLI 1.3及更高版本中已被弃用。在较新的版本中,您可以使用Option
类的构造函数创建选项。