How to fetch parameters when using the Apache Commons CLI library

后端 未结 2 537
旧巷少年郎
旧巷少年郎 2020-12-03 10:13

I\'m using the Apache Commons CLI to handle command line arguments in Java.

I\'ve declared the a and b options and I\'m able to access the

相关标签:
2条回答
  • 2020-12-03 10:44

    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;
    }
    
    0 讨论(0)
  • 2020-12-03 10:49

    Use the following method:

    CommandLine.getArgList()
    

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

    0 讨论(0)
提交回复
热议问题