-key = value格式的Java命令行参数

时间:2014-01-24 00:53:03

标签: java command-line

是否有一种智能/简单的方法来使用--key = value格式的命令行参数?我只是快速地检查了args [i]以查看它是否包含我的一个键,然后获取该键的值并为其设置变量,但是必须有一个更好的方法。我似乎无法通过谷歌搜索找到任何好的东西,所以我一定是在寻找错误的东西。任何想法/见解?

谢谢!

3 个答案:

答案 0 :(得分:19)

尝试-D选项,允许设置key = value对:

运行命令;请注意-Dkey

之间没有空格

java -Dday = Friday -Dmonth = Jan MainClass

在你的代码中:

String day = System.getProperty("day");
String month = System.getProperty("month");

答案 1 :(得分:0)

这会将具有 key = value 对的String[] args转换为Map。这里使用HashMap是因为它允许空值。

package org.company;

import java.util.HashMap;
import java.util.Map;

public class Main {
    /**
     * Convert an array of key=value pairs into a hashmap.
     * The string "key=" maps key onto "", while just "key" maps key onto null.
     * The value may contain '=' characters, only the first "=" is a delimiter.
     * @param args command-line arguments in the key=value format (or just key= or key)
     * @param defaults a map of default values, may be null. Mappings to null are not copied to the resulting map.
     * @param allowedKeys if not null, the keys not present in this map cause an exception (and keys mapped to null are ok)
     * @return a map that maps these keys onto the corresponding values.
     */
    static private HashMap<String, String> _parseArgs(String[] args, HashMap<String, String> defaults, HashMap<String, String> allowedKeys) {
        // HashMap allows null values
        HashMap<String, String> res = new HashMap<>();
        if (defaults != null) {
            for (Map.Entry<String, String> e : defaults.entrySet()) {
                if (e.getValue() != null) {
                    res.put(e.getKey(),e.getValue());
                }
            }
        }
        for (String s: args) {
            String[] kv = s.split("=", 2);
            if (allowedKeys != null && !allowedKeys.containsKey(kv[0])) {
                throw new RuntimeException("the key "+kv[0]+" is not in allowedKeys");
            }
            res.put(kv[0], kv.length<2 ? null : kv[1]);
        }
        return res;
    }

    /**
     * Compose a map to serve as defaults and/or allowedKeys for _parseArgs().
     * The string "key=" maps key onto "" that becomes the default value for the key,
     * while just "key" maps key onto null which makes it a valid key without any default value.
     * The value may contain '=' characters, only the first "=" is a delimiter.
     * @param args Strings in "key=value" (or "key=", or just "key") format.
     * @return a map that maps these keys onto the corresponding values.
     */
    static public HashMap<String, String> defaultArgs(String... args) {
        return _parseArgs(args, null, null);
    }

    /**
     * Convert an array of strings in the "key=value" format to a map.
     * If defaults is not null, the keys not present in this map cause an exception (and keys mapped to null are ok).
     * @param args the array that main(String[]) received
     * @param defaults specifies valid keys and their default values (keys mapped to null are valid, but have no default value)
     * @return a map that maps these keys onto the corresponding values.
     */
    static public HashMap<String, String> mapOfArgs(String[] args, HashMap<String, String> defaults) {
        return _parseArgs(args, defaults, defaults);
    }
    /**
     * Convert an array of strings in the "key=value" format to a map.
     * The keys not present in defaults are always ok.
     * @param args the array that main(String[]) received
     * @param defaults if not null, specifies default values for keys (keys mapped to null are ignored)
     * @return a map that maps these keys onto the corresponding values.
     */
    static public HashMap<String, String> uncheckedMapOfArgs(String[] args, HashMap<String, String> defaults) {
        return _parseArgs(args, defaults, null);
    }

    /**
     * Test harness
     * @param args
     */
    public static void main(String[] args) {
        Map<String, String> argMap = mapOfArgs(args, defaultArgs("what=hello","who=world","print"));
        for (Map.Entry<String,String> e : argMap.entrySet()) {
            System.out.println(""+e.getKey()+" => "+e.getValue()+";");
        }
    }

}

示例运行:

$ java org.company.Main 
what => hello;
who => world;
$ java org.company.Main print=x=y
print => x=y;
what => hello;
who => world;
$ java org.company.Main who=lambdas what=rule print
print => null;
what => rule;
who => lambdas;
$ java org.company.Main who=lambdas what=rule print=
print => ;
what => rule;
who => lambdas;
$ java org.company.Main get
Exception in thread "main" java.lang.RuntimeException: the key get is not in allowedKeys
    at org.company.Main._parseArgs(Main.java:37)
    at org.company.Main.mapOfArgs(Main.java:64)
    at org.company.Main.main(Main.java:9)

上面,由于默认值中没有"get",因此发生了异常。

如果我们使用uncheckedMapOfArgs()而不是mapOfArgs()

$ java org.company.Main get
what => hello;
get => null;
who => world;

答案 2 :(得分:0)

到目前为止,还没有办法将--key=value转换为Map而不是String。

public static void main(String[] args) {

    HashMap<String, String> params = convertToKeyValuePair(args);

    params.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));

}

private static HashMap<String, String> convertToKeyValuePair(String[] args) {

    HashMap<String, String> params = new HashMap<>();

    for (String arg: args) {

        String[] splitFromEqual = arg.split("=");

        String key = splitFromEqual[0].substring(2);
        String value = splitFromEqual[1];

        params.put(key, value);

    }

    return params;
}

希望这会有所帮助!