我已經看過文檔,但看不到如何讓Apache Commons CLI處理通常會終止選項處理的雙連字符「選項」。如何讓Apache CLI處理雙連擊?
考慮以下命令行,其具有「-opt」選項,可以採取未指定的可選參數:我要的選項與在這種情況下,沒有爭論最終
MyProgram -opt -- param1 param2
,但是Apache返回「 - 」作爲參數。如果該選項允許多於一個參數,則某些或全部參數將作爲參數返回。
這裏是說明問題的示例代碼:
package com.lifetouch.commons.cli;
import java.util.Arrays;
import org.apache.commons.cli.*;
public class DoubleHyphen {
private static Options options = new Options();
public static void main(String args[]) {
// One required option with an optional argument:
@SuppressWarnings("static-access")
OptionBuilder builder = OptionBuilder.isRequired(true).
withDescription("one optional arg").
withArgName("optArg").hasOptionalArgs(1);
options.addOption(builder.create("opt"));
// Illustrate the issue:
doCliTest(new String[] { "-opt"});
doCliTest(new String[] { "-opt", "optArg", "param"});
doCliTest(new String[] { "-opt", "--", "param"});
// What I want is for the double-dash to terminate option processing.
// Note that if "opt" used hasOptionalArgs(2) then "param" would be a second
// argument to that option (rather than an application parameter).
}
private static void doCliTest(String[] args) {
System.out.println("\nTEST CASE -- command line items: " + Arrays.toString(args));
// Parse the command line:
CommandLine cmdline = null;
try {
CommandLineParser parser = new GnuParser();
cmdline = parser.parse(options, args); // using stopAtNonOption does not help
} catch (ParseException ex) {
System.err.println("Command line parse error: " + ex);
return;
}
// Observe the results for the option and argument:
String optArgs[] = cmdline.getOptionValues("opt");
if (null == optArgs) {
System.out.println("No args specified for opt");
} else {
System.out.println(optArgs.length + " arg(s) for -opt option: " +
Arrays.toString(optArgs));
}
// Observe the results for the command-line parameters:
String tmp = Arrays.toString(cmdline.getArgList().toArray());
System.out.println(cmdline.getArgList().size() +
" command-line parameter(s): " + tmp);
}
}
您是否使用了最新的Apache的百科全書CLI ** ** 1.2版本? – 2012-01-26 13:04:58
是的,我正在使用1.2 – MykennaC 2012-01-26 15:01:54
然後下面的'PosixParser'應該可以工作。請參閱[PosixParser.java](http://javasourcecode.org/html/open-source/commons-cli/commons-cli-1.2/org/apache/commons/cli/PosixParser.java.html)源代碼:它處理用'--'(見第182行的private void processNonOptionToken(String value,boolean stopAtNonOption))。 – 2012-01-26 15:15:29