gpt4 book ai didi

java - 如何使用 Commons CLI 传递(和获取后)参数数组?

转载 作者:行者123 更新时间:2023-11-29 10:13:47 24 4
gpt4 key购买 nike

我有以下代码:

options.addOption(OptionBuilder.withLongOpt(SOURCES)
.withDescription("path to sources")
.hasArg()
.withArgName("PATHS")
.create());
...
CommandLineParser parser = new GnuParser();
line = parser.parse(options, args);
...
System.out.println(line.getOptionValues(SOURCES));

我用参数调用应用程序

-sources=path1, path2

在结果中我看到 ["path1"]

我想得到两个参数。我怎样才能通过它?

命令行应该怎么写

最佳答案

使参数值以空格分隔,而不是逗号分隔:

-source=path1 path2

此外,您需要使用 .hasArgs() 而不是 .hasArg() 来返回多个参数值。您还可以指定 .hasArgs(2) 以获得明确数量的参数值。这是一个工作示例:

输入:-source=path1 path2

public class Test {

public static void main(String[] args) {
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("sources").withDescription("path to sources").hasArgs().withArgName("PATHS").create());

CommandLineParser parser = new GnuParser();
CommandLine line = null;

try {
line = parser.parse(options, args, true);
} catch (ParseException exp) {
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}

System.out.println(Arrays.toString(line.getOptionValues("sources")));
}
}

输出:[路径1,路径2]

关于java - 如何使用 Commons CLI 传递(和获取后)参数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24394145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com