配置文件读取工具类

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 专门用于读取配置文件,提供访问配置文件的方法。
 * <pre>
 * 文件内容为键值对形式,格式:key=value
 * </pre>
 * @author zql
 * @createTime 2020-11-30 22:49:02
 * @version 1.1
 * @modifyLog 1.1 优化代码
 *
 */
public class ReadPropertiesUtil {

	private InputStream ins = null;
	
	private Properties pro = null;

	public ReadPropertiesUtil() {
	}

	/**
	 * @param pkg 所在包名,从src下开始,例如:top.zqlweb.config
	 * @param fileName 文件名
	 */
	public ReadPropertiesUtil(String pkg, String fileName) {
		// 配置文件所在路经
		String name = pkg.replaceAll("\\.", "/") + "/" + fileName + ".properties";
		this.ins = ReadPropertiesUtil.class.getClassLoader().getResourceAsStream(name);
		BufferedReader bf = new BufferedReader(new InputStreamReader(ins));
		this.pro = new Properties();
		try {
			this.pro.load(bf);
		} catch (IOException e) {
			System.out.println(name + "文件没有找到,请检查路径!");
			e.printStackTrace();
		}
	}

	/**
	 * 通过key查询相应的value
	 * @author zql
	 * @createTime 2020-11-30 22:50:01
	 *
	 * @param key
	 * @return
	 */
	public String getPropertys(String key) {
		return this.pro.getProperty(key);
	}

	/**
	 * 返回键值对大小
	 * @author zql
	 * @createTime 2020-11-30 22:50:17
	 *
	 * @return
	 */
	public int size() {
		return this.pro.size();
	}

	/**
	 * 返回所有键值对
	 * @author zql
	 * @createTime 2020-11-30 22:50:27
	 *
	 * @return
	 */
	public Map<String, String> getMap() {
		Map<String, String> map = new HashMap<String, String>();
		for (Map.Entry<Object, Object> m : this.pro.entrySet()) {
			map.put(m.getKey().toString(), m.getValue().toString());
		}
		return map;
	}

	/**
	 * 判断配置文件是否存在
	 * @author zql
	 * @createTime 2020-11-30 22:50:37
	 *
	 * @param filePath,从src下开始,格式:top/zqlweb/config/server.properties
	 * @return
	 */
	public boolean isExistProperties(String filePath) {
		String paths = System.getProperty("user.dir") + "\\src\\" + filePath.replaceAll("/", "\\\\");
		File file = new File(paths);
		return file.exists();
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值