JAVA 读取properties配置文件 - 全局搜索路径


import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

public class ParseProperties {

	private static final String DEFAULT_FILE = "dynamic.system.properties";
	
	private static Properties properties = null;
	
	private static final String DEFAULT_VALUE = "";
	
	//替换字符
	private static final String CHARACTER = "?";
		
	static{

		try {
			
			initializeProperties();
			
		} catch (IOException e) {
			
			e.printStackTrace();
			LogUtils.error("Initialization configuration file exception , Abnormal content :?", e);
		} 
	}
	
	public static String getProperty(String key) {
		
		try {
			
			
			return properties.getProperty(key);
		} catch (Exception e) {
			
			e.printStackTrace();
			LogUtils.error("Read the properties file is abnormal , Abnormal content :?", e);
		}
		
		return DEFAULT_VALUE;
	}
	
	public static String getProperty(String key , Object... obj) {
		
		try {
			
			String value = properties.getProperty(key);
			if(!StringUtils.isEmpty(value)){
				
				for (int i = 0; i < obj.length; i++) {

					value = replaceString(value, obj[i].toString());
				}
			}
			
			return value;
		} catch (Exception e) {
			
			e.printStackTrace();
			LogUtils.error("Read the properties file is abnormal , Abnormal content :?", e);
		}
		
		return DEFAULT_VALUE;
	}
	
	
	/**
	 * 初始化Properties对象
	 * @throws IOException
	 */
	public static void initializeProperties() throws IOException{

		if(properties == null){

			properties = PropertiesLoaderUtils.loadAllProperties(DEFAULT_FILE);
		}
	}
	
	/**
	 * 根据CHARACTER挨个替换内容
	 * @param msg 字符串
	 * @param replacement 替换内容
	 * @return String
	 */
    public static String replaceString(String msg, String replacement) {
    	
        String searchStr = CHARACTER;
        int index = msg.indexOf(searchStr);
 
        return msg.substring(0, index) + replacement + msg.substring(index + 1);
    }

	public static void main(String[] args) {
		System.out.println(SystemUtils.getProperty("system.no"));
		System.out.println(getProperty("system.exception","出错了"));
	}
}

你可能感兴趣的:(java)