zoukankan      html  css  js  c++  java
  • java 读取properties文件

     Tools :

      

    public static String getAutoLoadValueByKey(String configName,String key) 
    	{
    		return PropertiesAutoLoad.PROPERTIES.getValueFromPropFile(configName+".properties", key);
    	}
    

      

    调用方法:

      

    package com.mondial.emap.util;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.apache.commons.configuration.ConfigurationException;
    import org.apache.commons.configuration.PropertiesConfiguration;
    import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
    import org.apache.log4j.Logger;
    
    public enum PropertiesAutoLoad {
    	PROPERTIES;
    
    	private static final Logger log = Logger
    			.getLogger(PropertiesAutoLoad.class);
    
    	private final Map<String, PropertiesConfiguration> pptsMap = new HashMap<String, PropertiesConfiguration>();
    
    	/**
    	 * 根据属性文件和属性key获得对应的value
    	 * 
    	 * @param propertiesFile
    	 * @param key
    	 * @return value
    	 */
    	public String getValueFromPropFile(String propertiesFile, String key) {
    		this.load(propertiesFile);
    		PropertiesConfiguration ppts = pptsMap.get(propertiesFile);
    		if (ppts != null) {
    			return ppts.getString(key);
    		} else {
    			return null;
    		}
    	}
    
    	/**
    	 * 根据属性文件和属性key获得对应的value数组
    	 * 
    	 * @param propertiesFile
    	 * @param key
    	 * @return value array
    	 */
    	public String[] getArrayFromPropFile(String propertiesFile, String key) {
    		this.load(propertiesFile);
    		PropertiesConfiguration ppts = pptsMap.get(propertiesFile);
    		if (ppts != null) {
    			return ppts.getStringArray(key);
    		} else {
    			return null;
    		}
    	}
    
    	// 加载
    	private void load(String propertiesFile) {
    		if (!pptsMap.containsKey(propertiesFile)) {
    			synchronized (PropertiesAutoLoad.class) {
    				if (!pptsMap.containsKey(propertiesFile)) {
    					try {
    						PropertiesConfiguration propConfig = new PropertiesConfiguration(
    								propertiesFile);
    						// 设置重载策略
    						propConfig
    								.setReloadingStrategy(new FileChangedReloadingStrategy());
    						pptsMap.put(propertiesFile, propConfig);
    					} catch (ConfigurationException e) {
    						log.error(e.getMessage());
    					}
    				}
    			}
    		}
    	}
    }
    

      

    java代码中调用方法:

      Tools.getAutoLoadValueByKey("jlr", "workShopReturn");

    properties文件名为:“jlr”   文件内配置名称为:“workShopReturn”

    例如:workShopReturn=http://127.0.0.1:8080/send

      

  • 相关阅读:
    2001.3.9 每日总结
    2021.3.5
    2021.3.4每日总结
    2021.3.3每日总结
    每日总结2021.3.2
    2021.1.13
    2021.1.12
    PodPreset
    ingress-nginx安装
    RBAC
  • 原文地址:https://www.cnblogs.com/yangchengdebokeyuan/p/9450496.html
Copyright © 2011-2022 走看看