【问题标题】:Apache Common CLI doesn't recognize optionsApache Common CLI 无法识别选项
【发布时间】:2013-07-01 04:44:14
【问题描述】:

我尝试使用 Common CLI 解析简单的参数,但收到 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)。

【问题讨论】:

    标签: java command-line-arguments


    【解决方案1】:

    改变

        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 所期望的。

    【讨论】:

    • 哦,谢谢,这对我有用。没有关于如何将 args 传递给 commons-cli 的信息,并且有一个像 String[] args = new String[]{ "--block-size=10" }; 这样的示例让我感到困惑:)
    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 2014-02-13
    • 2014-08-21
    • 2020-07-02
    • 2018-02-06
    相关资源
    最近更新 更多