parse arguments nix-style. - Java java.lang

Java examples for java.lang:String Parse

Description

parse arguments nix-style.

Demo Code


//package com.java2s;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] args = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(parseArgs(args));
    }//from www.  j  av a  2 s .  co m

    /**
     * parse arguments nix-style.
     */
    public static Map<String, String> parseArgs(String[] args) {
        Map<String, String> param = new HashMap<String, String>();
        String otherArgs = "";
        String sep = "";
        for (int i = 0; i < args.length - 1; i++) {
            if (args[i].startsWith("--")) {
                param.put(args[i].substring(2), "");
            } else if (args[i].startsWith("-")) {
                param.put(args[i].substring(1), args[i + 1]);
                i++;
            } else {
                otherArgs += sep + args[i];//bouh, c'est mal, tant pis.
                sep = ",";
            }
        }
        if (args.length > 0) {
            if (args[args.length - 1].startsWith("--")) {

                param.put(args[args.length - 1].substring(2), "");
            } else {
                otherArgs += sep + args[args.length - 1];// bouh, c'est mal, tant pis.
                sep = ",";
            }
        }
        param.put("zargs", otherArgs);
        return param;

    }
}

Related Tutorials