使用 java.util.Properties 讀取配置文件中的參數


配置文件格式

如下的配置參數格式都支持:

Key = Value
Key =
Key:Value
Key  :Value

用法

getProperty方法的返回值是String類型。

        //讀取配置文件
        FileInputStream inStream = null;
        try {
            inStream = new FileInputStream("/fetchedfile/redis.conf");
            Properties prop = new Properties();
            prop.load(inStream);
            Field field;
            String property;
        //將配置參數讀到對象中
            for(Map.Entry<String, String> entry : RedisConstants.REDIS_PARAM.entrySet()){
                System.out.println(entry.getKey() + ": " + prop.getProperty(entry.getKey()));
                field = redisServiceParam.getClass().getDeclaredField(entry.getValue());
                field.setAccessible(true);
                //獲取參數
                property = prop.getProperty(entry.getKey());
                if(null == property || property.isEmpty()){
                    field.set(redisServiceParam, null);
                }else{
                    field.set(redisServiceParam, property);
                }
            }
        } catch (IOException | NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

 


免責聲明!

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



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