Properties类

1. Java Properties 类

Properties(Java.util.Properties)主要用于读取java的配置文件,通常读取.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

2. 成员方法

Properties主要包含以下几个成员方法:

  1. load ( InputStream inStream)
    用于从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。
  2. getProperty ( String key)
    从properties对象中去获取key对于的value值。
  3. setProperty ( String key, String value)
    在properties对象中去设置key/value值。

3. 读取Properties文件

load ( InputStream inStream)方法需要传入一个InputStream 类型的参数,该参数可以使用FileInputStream(new File(String path))去获得,更常用的是通过class.getResourceAsStream(String path)去获得。

4. 实例

public class PropsUtil {
	private static final Logger logger = LoggerFactory.getLogger(PropsUtil.class);
	
	public static Properties loadProps(String propsPath){
		Properties properties = new Properties();
		InputStream is = null;
		try {
			if(StringUtil.isEmpty(propsPath)){
				throw new IllegalArgumentException();
			}
			is = PropsUtil.class.getResourceAsStream(propsPath);
			if(is != null){
				properties.load(is);
			}
			
		} catch (Exception e) {
			logger.error("加载文件出错", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if(is != null){
					is.close();
				}
			} catch (Exception e) {
				logger.error("释放资源出错", e);
			}
		}
		return properties;
	}
	
	public static String getValue(Properties properties, String key){
		return properties.getProperty(key);
	}
	
	public static String getValue(Properties properties, String key, String defaultValue){
		String value = defaultValue;
		if(properties.containsKey(key)){
			value = properties.getProperty(key);
		}
		return value;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值