Parsing arguments to a Java command line program

后端 未结 9 995
孤街浪徒
孤街浪徒 2020-12-07 20:37

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:

9条回答
  •  独厮守ぢ
    2020-12-07 21:19

    You could use the refcodes-console artifact at refcodes-console on REFCODES.ORG:

    Option r     = new StringOptionImpl( "-r", null, "opt1", "..." );
    Option s     = new StringOptionImpl( "-S", null, "opt2", "..." );
    Operand arg1 = new StringOperandImpl( "arg1", "..." );
    Operand arg2 = new StringOperandImpl( "arg2", "..." );
    Operand arg3 = new StringOperandImpl( "arg3", "..." );
    Operand arg4 = new StringOperandImpl( "arg4", "..." );
    Switch test          = new SwitchImpl( null, "--test", "..." );
    Option a     = new StringOptionImpl( "-A", null, "opt3", "..." );
    Condition theRoot    = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
        test );
    

    Create your arguments parser ArgsParserImpl with your root condition:

    ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
    theArgsParser.setName( "MyProgramm" );
    theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );
    

    Above you define your syntax, below you invoke the parser:

    theArgsParser.printUsage();
    theArgsParser.printSeparatorLn();
    theArgsParser.printOptions();
    theArgsParser.evalArgs( new String[] {
        "-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444", 
        "--test", "-A", "AAAAA"
    } );
    

    In case you provided some good descriptions, theArgsParser.printUsage() will even show you the pretty printed usage:

    Usage: MyProgramm -r  -S  -A  arg1 arg2 arg3 arg4 --test
    

    In the above example all defined arguments must be passed by the user, else the parser will detect a wrong usage. In case the --test switch is to be optional (or any other argument), assign theRoot as follows:

    theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl( test ) );

    Then your syntax looks as follows:

    Usage: MyProgramm -r  -S  -A  arg1 arg2 arg3 arg4 [--test]
    

    The full example for your case you find in the StackOverFlowExamle. You can use AND, OR, XOR conditions and any kind of nesting ... hope this helps.

    Evaluate the parsed arguments as follows: r.getValue() ); or if (test.getValue() == true) ...:

    LOGGER.info( "r    :=" + r.getValue() );
    LOGGER.info( "S    :=" + s.getValue() );
    LOGGER.info( "arg1 :=" + arg1.getValue() );
    LOGGER.info( "arg2 :=" + arg2.getValue() );
    LOGGER.info( "arg3 :=" + arg3.getValue() );
    LOGGER.info( "arg4 :=" + arg4.getValue() );
    LOGGER.info( "test :=" + test.getValue() + "" );
    LOGGER.info( "A    :=" + a.getValue() );
    

提交回复
热议问题