org.apache.commons.cli.Options


在使用java -jar命令執行包時,使用Options封裝一些參數,
如下方法中使用:
public static void run(String[] args)  {
    if (args.length > 0) {
        Properties properties = new Properties();
        Options options = new Options();
        options.addOption("M", true, "main app classname");
        options.addOption("P", true, "properties filename");
        OptionBuilder.withArgName("property=value");
        OptionBuilder.hasArgs(2);
        OptionBuilder.withValueSeparator();
        OptionBuilder.withDescription("use value for given property");
        options.addOption(OptionBuilder.create("D"));
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = null;
        try{
           cmd =  parser.parse(options, args);
        }catch (ParseException e){
            e.printStackTrace();
        }
        if (cmd.hasOption('M')) {
            String fullClassName = cmd.getOptionValue('M');
            if (fullClassName != null && !fullClassName.isEmpty()) {
                if (cmd.hasOption('P')) {
                    File file = new File(cmd.getOptionValue('P'));
                    try{
                        FileInputStream fStream = new FileInputStream(file);
                        try {
                            properties.load(fStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }catch (FileNotFoundException e1){
                        e1.printStackTrace();
                    }
                }
                properties.putAll(cmd.getOptionProperties("D"));
                properties.setProperty("conf.app.startup.timestamp", String.valueOf((new Date()).getTime())); //當前時間戳加入到配置中
                logger.info("properties:"+properties.toString());
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM