gst*_*low 2 java command-line command-line-interface command-line-arguments
我有以下代码:
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]
如果要传递数组,则应替换hasArg()为hasArgs()以指示该选项可能具有多个值。现在你可以像这样传递它们:
-sources path1 path2
如果您希望能够以逗号分隔传递它们,您可以调用withValueSeparator(',')您的OptionBuilder,从而生成如下代码:
options.addOption(OptionBuilder.withLongOpt(SOURCES)
    .withDescription("path to sources")
    .hasArgs()
    .withValueSeparator(',')
    .withArgName("PATHS")
    .create());
现在你可以通过这种方式传递它们:
-sources path1,path2
但是请记住,该空间仍将被视为分隔符。