Java读常用配置文件properties的方法

有两种方法:第一种直接使用,第二种封装的好点。

1


	// 代表静态资源路径
	private static String WEB_ROOT = System.getProperty("user.dir") + "\\" + "src\\main\\webapp";

	// 还要将配置文件中的信息读取到map中
	private static Map<String, String> map = new HashMap<String, String>();
	
	// 访问之前初始化配置信息到map中
	static {
		// 使用javaAPI读取配置文件信息
		Properties prop = new Properties();

		try {
			// 先加载
			prop.load(new FileInputStream(WEB_ROOT + "\\conf.properties"));

			// 将配置文件中的数据读取到map中、
			Set set = prop.keySet();
			Iterator iterator = set.iterator();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				String value = prop.getProperty(key);
				map.put(key, value);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

2

这种先写一个类继承Properties

package com.yuer.mytomcat.yc;


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

/**
 * 读取配置文件
 * @author Yuer
 *
 */
public class ReadConfig extends Properties{
	private static final long serialVersionUID = 4896442440078075125L;
	private static ReadConfig instance = new ReadConfig();
	
	private ReadConfig() {
		try(InputStream is = this.getClass().getClassLoader().getResourceAsStream("application.properties");) {
			this.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static ReadConfig getInstance() {
		return instance;
	}
}


再使用,这种封装得好些。

ReadConfig.getInstance().getProperty("aa");
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值