Java Args Parse parseCommandLineArguments(String[] args)

Here you can find the source of parseCommandLineArguments(String[] args)

Description

A simpler form of command line argument parsing.

License

Apache License

Parameter

Parameter Description
args a parameter

Return

A Map from keys to possible values (String or null)

Declaration

public static Map parseCommandLineArguments(String[] args) 

Method Source Code

//package com.java2s;
/*//  w w w  .j a v a2  s  .com
 *  * Copyright 2016 Skymind, Inc.
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *        http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * A simpler form of command line argument parsing.
     * Dan thinks this is highly superior to the overly complexified code that
     * comes before it.
     * Parses command line arguments into a Map. Arguments of the form
     * -flag1 arg1 -flag2 -flag3 arg3
     * will be parsed so that the flag is a key in the Map (including the hyphen)
     * and the
     * optional argument will be its value (if present).
     *
     * @param args
     * @return A Map from keys to possible values (String or null)
     */
    public static Map parseCommandLineArguments(String[] args) {
        Map<String, String> result = new HashMap<>();
        String key, value;
        for (int i = 0; i < args.length; i++) {
            key = args[i];
            if (key.charAt(0) == '-') {
                if (i + 1 < args.length) {
                    value = args[i + 1];
                    if (value.charAt(0) != '-') {
                        result.put(key, value);
                        i++;
                    } else {
                        result.put(key, null);
                    }
                } else {
                    result.put(key, null);
                }
            }
        }
        return result;
    }
}

Related

  1. parseArgs(String[] args)
  2. parseArguments(final String[] args)
  3. parseArguments(String[] args)
  4. parseCLInput(String[] args)
  5. parseCommandLine(String[] args)
  6. parseCommandLineArguments(String[] args)
  7. parseLines(String[] lines)
  8. parseProgramArguments(String[] args)
  9. parseProviderOptions(String[] options)