JavaWeb读取配置文件工具类

该博客介绍了如何使用Java的Properties类来读取配置文件,并提供了PropertiesUtil工具类的实现,便于多次读取。文章讲解了工具类的构造方法、单例模式以及获取属性值的方法,展示了如何在代码中静态或非静态地调用配置信息。
摘要由CSDN通过智能技术生成

 1.读取配置文件的方法:

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * properties解析工具
 * 
 * @author xxxx
 * 
 */
public class PropertiesUtil {
	private static Map<String, PropertiesUtil> propertiesUtilMap = new HashMap<String, PropertiesUtil>();
	private Map<String, String> proMap = new HashMap<String, String>();

	private PropertiesUtil(String propertiesFilePath) {
		InputStream is = null;
		try {
			Properties pro = new Properties();
			is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/conf/" + propertiesFilePath);
			pro.load(is);
			Enumeration<?> e = pro.propertyNames();
			while (e.hasMoreElements()) {
				String key = (String) e.nextElement();
				String value = (String) pro.get(key);
				proMap.put(key, value);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}  finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static PropertiesUtil getInstance(String propertiesFileName) {
		PropertiesUtil propertiesUtil = null;
		if (propertiesUtilMap.containsKey(propertiesFileName)) {
			propertiesUtil = propertiesUtilMap.get(propertiesFileName);
		} else {
			propertiesUtil = new PropertiesUtil(propertiesFileName);
			propertiesUtilMap.put(propertiesFileName, propertiesUtil);
		}
		return propertiesUtil;
	}

	/**
	 * 获取所有key-value
	 * @return
	 */
	public Map<String, String> getProMap() {
		return proMap;
	}

	/**
	 * 根据key获取value
	 * @param key
	 * @return
	 */
	public String getKey(String key) {
		return proMap.get(key);
	}

2.使用方式:

//如果使用频繁,声明全局静态变量
private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("xxx.properties");
private static String name = propertiesUtil.getKey("name");
... ...


//如果使用不频繁,声明全局变量
private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("xxx.properties");


//在方法里面调用
String url = properties.getKey("name");

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早退的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值