How to fetch parameters when using the Apache Commons CLI library

喜夏-厌秋 提交于 2019-11-27 14:19:52

Use the following method:

CommandLine.getArgList()

which returns whatever's left after options have been processed.

It may be better to use another Option (-d) to identify directory which is more intuitive to the user.

Or the following code demonstrates getting the remaining argument list

public static void main(final String[] args) {
    final CommandLineParser parser = new BasicParser();
    final Options options = new Options();
    options.addOption("a", "opta", true, "Option A");
    options.addOption("b", "optb", true, "Option B");

    final CommandLine commandLine = parser.parse(options, args);

    final String optionA = getOption('a', commandLine);
    final String optionB = getOption('b', commandLine);

    final String[] remainingArguments = commandLine.getArgs();

    System.out.println(String.format("OptionA: %s, OptionB: %s", optionA, optionB));
    System.out.println("Remaining arguments: " + Arrays.toString(remainingArguments));
}

public static String getOption(final char option, final CommandLine commandLine) {

    if (commandLine.hasOption(option)) {
        return commandLine.getOptionValue(option);
    }

    return StringUtils.EMPTY;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!