How do I parse command line arguments in Java?

前端 未结 19 1680
终归单人心
终归单人心 2020-11-22 00:16

What is a good way of parsing command line arguments in Java?

19条回答
  •  情话喂你
    2020-11-22 00:45

    I know most people here are going to find 10 million reasons why they dislike my way, but nevermind. I like to keep things simple, so I just separate the key from the value using a '=' and store them in a HashMap like this:

    Map argsMap = new HashMap<>();
    for (String arg: args) {
        String[] parts = arg.split("=");
        argsMap.put(parts[0], parts[1]);
    } 
    

    You could always maintain a list with the arguments you are expecting, to help the user in case he forgot an argument or used a wrong one... However, if you want too many features this solution is not for you anyway.

提交回复
热议问题