Apache Common CLI无法识别选项

时间:2013-07-03 13:08:37

标签: java command-line-arguments

我尝试使用Common CLI解析简单的args但接收ParseException。

这是我的代码:

@SuppressWarnings("static-access")
public class CmdParsingTest {
    private static final Options options;

    static {
        options = new Options();
        options.addOption(OptionBuilder.withLongOpt("schema-file")
                .withDescription("path to schema file")
                .hasArg()
                .withArgName("schemaFile")
                .create("source"));
        options.addOption( OptionBuilder.withLongOpt("state-url")
                .withDescription("state url")
                .hasArg()
                .withArgName("stateUrl")
                .create("url"));
        options.addOption( OptionBuilder.withLongOpt("update-number")
                .withDescription("update number to start from")
                .hasArg()
                .withArgName("updateNum")
                .create("update"));
        options.addOption(OptionBuilder.withLongOpt("result-file")
                .withDescription("use given file to save result")
                .hasArg()
                .withArgName("resultFile")
                .create("result"));
    }

    public static void main(String[] args) {
        args = new String[]{
                "-source /home/file/myfile.txt",
                "-url http://localhost/state",
                "-result result.txt"};
        // create the parser
        CommandLineParser parser = new BasicParser();
        try {
            // parse the command line arguments
            CommandLine cmd = parser.parse(options, args);
            //other cool code...    
        }
        catch( ParseException exp ) {
            System.err.println( "Parsing of command line args failed.  Reason: " + exp.getMessage() );
        }
    }
}

结果是:

  

解析命令行参数失败。原因:无法识别的选项:-source /home/file/myfile.txt

如果我使用没有破折号的args,则抛出没有异常,但cmd.hasOption("source")返回false。

P.S>使用示例建议使用DefaultParser,但它仅出现在CLI 1.3中(根据1.3 JavaDoc)。

1 个答案:

答案 0 :(得分:8)

更改

    args = new String[]{
            "-source /home/file/myfile.txt",
            "-url http://localhost/state",
            "-result result.txt"};

    args = new String[]{
            "-source", "/home/file/myfile.txt",
            "-url", "http://localhost/state",
            "-result", "result.txt"};

第二个是JVM如何将命令行参数打包/传递给你的main方法,因此是commons-cli所期望的。