⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 config.java

📁 在线考试系统
💻 JAVA
字号:
package com.nc21.exam.util;

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

import org.apache.log4j.Logger;

/**
 * 该类用于获取config.properties中的配置属性
 * 
 * @author Administrator
 * 
 */
public class Config {

	private final static Logger log = Logger.getLogger(Config.class);

	/**
	 * 按预定时间自动检查属性配置文件是否发生了改变, 若改变则重新载入。
	 * 
	 * @author Administrator
	 * 
	 */
	public static class AutoReloadPropertiesTimerTask extends TimerTask {

		@Override
		public void run() {
			if (propertiesFile != null) {
				long tmpModified = propertiesFile.lastModified();
				if (tmpModified > lastModified) {
					loadProperties(properties);
					lastModified = propertiesFile.lastModified();
					log.info("Auto reload the config file.");
				}
			}
		}

	}

	private static Properties properties;

	private static Timer timer;

	private static File propertiesFile;

	private static FileInputStream propertiesFileInputStream;

	private static long lastModified;

	private static String realPath;

	public static void init(String path) {
		timer = new Timer(true);
		startReloadListening();
		propertiesFile = new File(path + "/config.properties");
		lastModified = propertiesFile.lastModified();
		realPath = path;
	}

	/**
	 * 开始启动检查属性是否已经更改的Timer
	 */
	private static void startReloadListening() {
		timer.schedule(new AutoReloadPropertiesTimerTask(), 2000, 2000);
	}

	/**
	 * 用户通过传入属性的名字,来获得属性的值
	 * 
	 * @param key
	 *            属性的名字
	 * @return
	 */
	public static String getValue(Object key) {
		if (properties == null) {
			properties = new Properties();
			loadProperties(properties);
		}
		return properties.getProperty(key.toString());
	}

	/**
	 * 向当前属性集中加一条属性
	 * 
	 * @param key
	 *            属性key
	 * @param value
	 *            属性值
	 */
	public static void addProperty(String key, Object value) {
		if ((key == null) || (value == null)) {
			throw new IllegalArgumentException();
		}
		properties.put(key, value);
	}

	/**
	 * @param properties
	 */
	private static void loadProperties(Properties properties) {
		try {
			if (propertiesFileInputStream == null) {
				propertiesFileInputStream = new FileInputStream(propertiesFile);
			}
			properties.load(new FileInputStream(propertiesFile));
			propertiesFile = new File(realPath + "/config.properties");
		} catch (FileNotFoundException e) {
			// 属性文件不存在异常处理
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}

	public static String getRealPath() {
		return realPath;
	}

	public static void setRealPath(String realPath) {
		Config.realPath = realPath;
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -