如何使用commons-cli解析java命令行?

阅读更多

Apache的Commons-CLI 包很好用,可以对命令行参数进行解析和类型转化。

public CliUtil(String[] args) {
        try {
            Options options = new Options();
            options.addOption(new Option("ip", "text", true, "ip must input!"));
            options.addOption(new Option("port", "text", true, "http port must input!"));
            options.addOption(new Option("zkHost", "text", true, "zk host must input!"));

            CommandLineParser parser = new BasicParser();
            CommandLine cmd = null;
            //args = new String[]{"-ip","192.168.28.86","-port","8085","-zkHost","10.167.253.01"};
            try {
                cmd = parser.parse(options, args);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            ip = cmd.getOptionValue("ip");
            port = Integer.parseInt(cmd.getOptionValue("port"));
            zkHost = cmd.getOptionValue("zkHost");

            if (StringUtils.isEmpty(ip) || port == 0 ||StringUtils.isEmpty(zkHost)) {
                throw new Exception();
            }

        } catch (Exception e) {
            logger.error("输入参数初始化失败!", e);
            System.exit(0);
        }
    }

 

你可能感兴趣的:(commons-cli,解析命令行参数)