修改配置不用重启服务的一种配置文件读取方式

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * 加载socket配置文件.
 * 
 */
public final class LoadConfigUtil {

	/**
	 * 属性文件全名"config/XXXX.properties".
	 */
	private static final String PFILE = "config/test.properties";

	/**
	 * 配置文件.
	 */
	private Properties properties = null;

	/**
	 * 对应属性文件.
	 */
	private File file = null;

	/**
	 * 属性最后修改日期.
	 */
	private long lastModifiedTime = 0;

	/**
	 *单例.
	 */
	private static LoadConfigUtil instance = new LoadConfigUtil();

	/**
	 * 私有构造方法.
	 */
	private LoadConfigUtil() {
		file = new File(PFILE);

		lastModifiedTime = file.lastModified();

		if (lastModifiedTime == 0) {
			System.err.println(PFILE + "配置文件不存在");
		}

		try {
			properties = new Properties();
			properties.load(new FileInputStream(PFILE));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获得单例.
	 * 
	 * @return instance.
	 */
	public static synchronized LoadConfigUtil getInstance() {
		return instance;
	}

	/**
	 * 获得文件属性.
	 * 
	 * @param name
	 *            参数名.
	 * @param defaultVal
	 *            默认值.
	 * @return 属性值.
	 */
	public String getConfigItem(String name, String defaultVal) {

		long newTime = file.lastModified();

		System.out.println("newtime:" + newTime);
		System.out.println("lastime:" + lastModifiedTime);
		// 检查属性文件是否被修改 ture则重新读取文件
		if (newTime == 0) {
			if (lastModifiedTime == 0) {
				System.err.println(PFILE + "配置文件不存在");
			} else {
				System.err.println(PFILE + "配置文件被删除");
			}
			return defaultVal;
		} else if (newTime > lastModifiedTime) {
			properties.clear();
			try {
				properties.load(new FileInputStream(PFILE));
				lastModifiedTime = newTime;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		String val = properties.getProperty(name);
		if (val == null) {
			return defaultVal;
		} else {
			return val;
		}
	}

	public String getXxx() {
		return getConfigItem("xxx", "");
	}

	public static void main(String[] args) throws InterruptedException {
		String result = LoadConfigUtil.getInstance().getXxx();
		System.out.println(result);

		Thread.sleep(10000);

		result = LoadConfigUtil.getInstance().getXxx();
		System.out.println(result);
	}

}


演示,在程序休眠期间,修改配置文件,即可得到新结果

newtime:1386732846531
lastime:1386732846531
6
newtime:1386931021114
lastime:1386732846531
7




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值