java 读取配置文件(一)
来源:互联网 发布:数据冗余类型 编辑:程序博客网 时间:2024/04/30 02:37
package com.xxx.config;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;import org.apache.log4j.Logger;/** * 读配置集成类<br> * @author */public class Configs { static Logger log = Logger.getLogger(Configs.class.getName()); private Properties props = null; protected void init(String file) { this.init(file, props); } protected void init(String file, Properties defaul) { File f = new File(file); if (f.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(f); } catch(FileNotFoundException e2) { e2.printStackTrace(); throw new ConfigException(e2); } props = new Properties(defaul); try { props.load(fis); fis.close(); } catch(IOException e) { e.printStackTrace(); throw new ConfigException(e); } } else { System.out.println(file + "配置文件没有找到!"); throw new ConfigException(file + "配置文件没有找到!"); } } /** * 得到包含配置信息的Properties对象 * @return Properties对象 */ public Properties getConfigProperty() { return props; } /** * 根据配置节点名得到配置值 * @param key 配置节点名 * @param defaul 默认值 * @param islog 是否写日志。如果为true且返回的配置值为null,则写日志 * @return 如果有配置值,则返回配置值,否则返回默认值 */ public String getConfig(String key, String defaul, boolean isLog) { String keyVal = props.getProperty(key); if (keyVal == null && isLog) { log.error("配置文件中没有名为:" + key + "的KEY值!"); } if (keyVal == null) { keyVal = defaul; } if (keyVal != null && keyVal.endsWith("\"")) keyVal = keyVal.replaceAll("\"", ""); return keyVal; } /** * 根据配置节点名得到配置值 * @param key 配置节点名 * @param defaul 默认值 * @return 如果有配置值,则返回配置值,否则返回默认值 */ public String getConfig(String key, String defaul) { return getConfig(key, defaul, false); } /** * 根据配置节点名得到配置值 * @param key 配置节点名 * @return 配置值 */ public String getConfig(String key) { return getConfig(key, null, false); } /** * 根据配置节点名得到配置值 * @param key 配置节点名 * @param islog 是否写日志。如果为true且返回的配置值为null,则写日志 * @return 配置值 */ public String getConfig(String key, boolean islog) { return getConfig(key, null, islog); }}