Parsing arguments to a Java command line program

后端 未结 9 987
孤街浪徒
孤街浪徒 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:10

    I like this one. Simple, and you can have more than one parameter for each argument:

    final Map> params = new HashMap<>();
    
    List options = null;
    for (int i = 0; i < args.length; i++) {
        final String a = args[i];
    
        if (a.charAt(0) == '-') {
            if (a.length() < 2) {
                System.err.println("Error at argument " + a);
                return;
            }
    
            options = new ArrayList<>();
            params.put(a.substring(1), options);
        }
        else if (options != null) {
            options.add(a);
        }
        else {
            System.err.println("Illegal parameter usage");
            return;
        }
    }
    

    For example:

    -arg1 1 2 --arg2 3 4
    
    System.out.print(params.get("arg1").get(0)); // 1
    System.out.print(params.get("arg1").get(1)); // 2
    System.out.print(params.get("-arg2").get(0)); // 3
    System.out.print(params.get("-arg2").get(1)); // 4
    

提交回复
热议问题