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

本文介绍了一个Java程序中用于解析属性文件的方法。通过使用Spring框架的支持工具加载默认的属性文件,并提供静态方法获取属性值,支持参数替换。适用于需要读取配置文件的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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","出错了"));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值