读取config 工具类

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 * 负责提取配置文件信息,并监测配置文件的改动
 *
 * @author lvlj
 * @datetime 2008-6-4 上午11:50:41
 */
public class ConfigUtil {

	public final static String CONFIG_FILE = "/config.properties";
	private static long lastModified = 0L;
	private static File configFile = null;

	private static Logger log = Logger.getLogger(ConfigUtil.class);
	private static Properties props = new Properties();

	static {
		loadProperty();
	}

	/**
	 * 从配置文件中读取所有的属性
	 */
	private static void loadProperty() {
		try {
			System.out.println(ConfigUtil.class.getResource(CONFIG_FILE).getPath());
			String path = ConfigUtil.class.getResource(CONFIG_FILE).getFile();
			if (System.getProperty("os.name").startsWith("Windows")) {
				path = path.substring(1);
				path = path.replaceAll("%20", " ");
			}
			File f = new File(path);

			lastModified = f.lastModified();
			configFile = f;
			log.info("load config from: " + f.getAbsolutePath());
			props.load(new FileInputStream(f));
			//(new ReloadThread()).start();
		} catch (Exception e) {
			log.error("load config falied!", e);
			System.exit(-1);
		}
	}

	/**
	 * 检测config文件是否被改动,改动后立即更新
	 */
	private static void checkUpdate() {
		if (configFile != null) {
			long m = configFile.lastModified();
			if (m != lastModified) {
				lastModified = m;
				try {
					Properties prop = new Properties();
					prop.load(new FileInputStream(configFile));
					props = prop;
					log.info("reload config file:" + configFile.getAbsolutePath());
				} catch (Exception e) {
					log.error("failed to reload config file: " + configFile.getAbsolutePath(), e);
				}
			}
		}
	}

	/**
	 * 根据属性名获得对应值,如果得不到值返回defaultValue
	 */
	public static String getConfig(String name, String defaultValue) {
		checkUpdate();
		String ret = props.getProperty(name, defaultValue);
		if (ret == null) {
			return defaultValue;
		} else {
			return ret.trim();
		}
	}

	public static String getConfig(String name) {
		return getConfig(name, null);
	}

	/**
	 * 检测config文件是否被改动的线程,每5秒检测一次
	 */
	static class ReloadThread extends Thread {
		public void run() {
			log.info("update checking for config file: " + configFile.getAbsolutePath());
			while (true) {
				System.out.println("dfghjkllkjhgfdfghj");
				if (configFile != null) {
					long m = configFile.lastModified();
					if (m != lastModified) {
						lastModified = m;
						try {
							Properties prop = new Properties();
							prop.load(new FileInputStream(configFile));
							props = prop;
							log.info("config file changed, reload: " + configFile.getAbsolutePath());
						} catch (Exception e) {
							log.error("failed to reload config file: " + configFile.getAbsolutePath(), e);
						}
					}
					try {
						Thread.sleep(5000);
					} catch (Exception e) {
						log.error("", e);
					}
				} else
					break;
			}
		}
	}

}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.File; import java.io.FileInputStream; import java.util.Properties; public class ReadConfigation{ /** * 属性文件全名 */ private static final String PFILE ="Config.properties"; /** * 对应于属性文件的文件对象变量 */ private File m_file = null; /** * 属性文件的最后修改日期 */ private long m_lastModifiedTime = 0; /** * 属性文件所对应的属性对象变量 */ private Properties m_props = null; /** * 本类可能存在的惟一的一个实例 */ private static ReadConfigation m_instance =new ReadConfigation(); /** * 私有的构造子,用以保证外界无法直接实例化 */ private ReadConfigation() { m_file = new File(PFILE); m_lastModifiedTime = m_file.lastModified(); if(m_lastModifiedTime == 0){ System.err.println(PFILE +" file does not exist!"); } m_props = new Properties(); try { m_props.load(new FileInputStream(PFILE)); } catch(Exception e) { e.printStackTrace(); } } /** * 静态工厂方法 * @return 返还ReadConfigation 类的单一实例 */ synchronized public static ReadConfigation getInstance() { return m_instance; } /** * 读取一特定的属性项 * * @param name 属性项的项名 * @param defaultVal 属性项的默认值 * @return 属性项的值(如此项存在), 默认值(如此项不存在) */ public String getConfigItem(String name,String defaultVal) { long newTime = m_file.lastModified(); // 检查属性文件是否被其他程序 // 如果是,重新读取此文件 if(newTime == 0) { // 属性文件不存在 if(m_lastModifiedTime == 0){ System.err.println(PFILE+ " file does not exist!"); }else{ System.err.println(PFILE+ " file was deleted!!"); } return defaultVal; }else if(newTime > m_lastModifiedTime){ // Get rid of the old properties m_props.clear(); try { m_props.load(new FileInputStream(PFILE)); }catch(Exception e){ e.printStackTrace(); } } m_lastModifiedTime = newTime; String val = m_props.getProperty(name); if( val == null ) { return defaultVal; } else { return val; } } /** * 读取一特定的属性项 * * @param name 属性项的项名 * @return 属性项的值(如此项存在), 空(如此项不存在) */ public String getConfigItem(String name){ return getConfigItem(name,""); } }
以下是一个Java配置文件分段读取工具类,可以将配置文件按照section分段读取,每个section中的键值对以Map的形式存储: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ConfigParser { private String filename; private Map<String, Map<String, String>> sections; public ConfigParser(String filename) throws IOException { this.filename = filename; this.sections = new HashMap<>(); parse(); } public String get(String section, String option) { Map<String, String> options = sections.get(section); if (options != null) { return options.get(option); } return null; } public void set(String section, String option, String value) { Map<String, String> options = sections.computeIfAbsent(section, k -> new HashMap<>()); options.put(option, value); } private void parse() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String line; String section = null; Map<String, String> options = new HashMap<>(); while ((line = br.readLine()) != null) { line = line.trim(); if (line.matches("\\[.*\\]")) { if (section != null) { sections.put(section, options); } section = line.substring(1, line.length() - 1); options = new HashMap<>(); } else if (line.matches(".*=.*")) { String[] parts = line.split("=", 2); String option = parts[0].trim(); String value = parts[1].trim(); options.put(option, value); } } if (section != null) { sections.put(section, options); } } } } ``` 使用示例: ```java public static void main(String[] args) throws IOException { ConfigParser config = new ConfigParser("config.ini"); String value = config.get("section1", "option1"); System.out.println(value); config.set("section2", "option2", "value2"); // ... } ``` 其中,`config.ini`配置文件的格式如下: ``` [section1] option1 = value1 option2 = value2 [section2] option3 = value3 option4 = value4 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值