java 读取配置文件(一)

本文详细介绍了如何读取和解析配置文件,包括文件存在性检查、文件输入流的使用、Properties对象初始化以及配置值获取等功能。
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);
    }

}











                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值