解析Java命令行程序的参数 [英] Parsing arguments to a Java command line program
问题描述
如果我想解析这个怎么办:
What if I wanted to parse this:
java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3
我想在程序中得到的结果是:
And the result I want in my program is:
regular Java args[] of size=4
org.apache.commons.cli.Options[] of size=3
org.apache.commons.cli.Options[] #2 of size=1
我更愿意使用< a href =http://commons.apache.org/cli/ =noreferrer> Apache Commons CLI ,但文档对我上面提到的案例有点不清楚。具体来说,文档没有告诉您如何处理我在下面指定的第三种类型的选项:
I would prefer to use Apache Commons CLI, but the documentation is a little unclear about the case I present above. Specifically, the documentation doesn't tell you how to handle options of the 3rd type I specify below:
1. options with a "-" char
2. options with a "--" char
3. options without any marker, or "bare args"
我希望Apache Commons CLI能够正常工作,但是如果那些args没有,那么STILL能够将常规args传递给程序选项前缀。也许它确实如此,但文档并没有这么说,因为我通读它...
I wish that Apache Commons CLI would work but STILL be able to pass regular args to the program if those args didn't have a option prefix. Maybe it does but the documentation doesnt say so as I read through it...
推荐答案
你可以手动完成。
NB:可能更好地使用HashMap而不是opts的内部类。
NB: might be better to use a HashMap instead of an inner class for the opts.
/** convenient "-flag opt" combination */
private class Option {
String flag, opt;
public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }
}
static public void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<Option> optsList = new ArrayList<Option>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].length < 2)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
if (args[i].charAt(1) == '-') {
if (args[i].length < 3)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
// --opt
doubleOptsList.add(args[i].substring(2, args[i].length));
} else {
if (args.length-1 == i)
throw new IllegalArgumentException("Expected arg after: "+args[i]);
// -opt
optsList.add(new Option(args[i], args[i+1]));
i++;
}
break;
default:
// arg
argsList.add(args[i]);
break;
}
}
// etc
}
这篇关于解析Java命令行程序的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!