java 使用 Apache Commons CLI 库时如何获取参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4689497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch parameters when using the Apache Commons CLI library
提问by Mridang Agarwalla
I'm using the Apache Commons CLI to handle command line arguments in Java.
我正在使用 Apache Commons CLI 来处理 Java 中的命令行参数。
I've declared the a
and b
options and I'm able to access the value using CommandLine.getOptionValue()
.
我已经声明了a
和b
选项,并且可以使用CommandLine.getOptionValue()
.
Usage: myapp [OPTION] [DIRECTORY]
Options:
-a Option A
-b Option B
How do I declare and access the DIRECTORY variable?
如何声明和访问 DIRECTORY 变量?
回答by Jim Garrison
Use the following method:
使用以下方法:
CommandLine.getArgList()
which returns whatever's left after options have been processed.
它返回处理选项后剩下的任何内容。
回答by Nauman
It may be better to use another Option (-d) to identify directory which is more intuitive to the user.
最好使用另一个选项 (-d) 来标识对用户更直观的目录。
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;
}