java读取properties文件

本文介绍Java中Properties文件的格式及使用方式,提供了一个实用工具类用于读取配置信息,适用于多种应用场景。

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

   java的配置文件除了xml外还可以是properties文件,properties文件的文件格式如下,由一个个键值对组成:


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/dbname?autoReconnect=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
jdbc.maxIdle=2

    

     读取properties文件的方法变化一般不大,所以在这里可以写一个工具类:


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {   
	private static String defaultPropertyFilePath = "test.properties";   
	private static Map<String,Properties> ppsMap = new HashMap<String,Properties>();
	
	/**  
	 * 读取默认文件的配置信息,读key返回value  
	 * @param key  
	 * @return value  
	 * @throws FileNotFoundException 
	*/  
	public static final String getPropertyValue(String key) throws FileNotFoundException {   
		Properties pps = getPropertyFile(defaultPropertyFilePath);   
		return pps == null ? null : pps.getProperty(key);   
	}   
       
	/**  
	* 传入filePath读取指定property文件,读key返回value  
	* @param propertyFilePath  
	* @param key  
	* @return value  
	 * @throws FileNotFoundException 
	*/  
	public static String getPropertyValue(String propertyFilePath,String key) throws FileNotFoundException {   
		if(propertyFilePath == null) {   
			propertyFilePath = defaultPropertyFilePath;   
		}   
		Properties pps = getPropertyFile(propertyFilePath);   
		return pps == null ? null : pps.getProperty(key);   
	}  
	
	/**  
	* 根据path返回property文件,并保存到HashMap中,提高效率  
	* @param propertyFilePath  
	* @return  
	 * @throws FileNotFoundException 
	*/  
	public static Properties getPropertyFile(String propertyFilePath) throws FileNotFoundException {   
		if(propertyFilePath == null) {   
			return null;   
		}
		Properties pps = ppsMap.get(propertyFilePath);   
		if(pps == null) {   
			InputStream in = new BufferedInputStream(new FileInputStream(propertyFilePath));
			pps = new Properties();
			try {   
				pps.load(in);   
	        } catch (IOException e) {   
	        	e.printStackTrace();   
	        }   
	        ppsMap.put(propertyFilePath, pps);   
		}   
		return pps;   
	}   
}
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值