配置文件读取JAVA工具类


    系统开发的时候,都会涉及到一些配置文件的读取,为方便从配置文件中读取我们预先设置的值,我做了一个简单配置文件读取工具类。这个类主要基于apache开源项目commons-configuration,让我们看下这个简单工具类的实现。

/**
 * Copyright(c) 2005 zjhcsoft Techonologies, Ltd.
 *
 * History:
 *   2010-3-4 14:10:33 Created by Tiwen
 */
package com.zjhcsoft.modules.configuration;
 
import java.util.Iterator;
import java.util.List;
 
import org.apache.commons.configuration.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import com.zjhcsoft.common.util.StringUtil;
 
 
 
/**
 * 系统配置文件参获取类
 *
 * @author <a href="mailto:Tiwen@qq.com">Tiwen</a>
 * @version 1.0 2010-3-4 14:10:33
 */
public class SystemConfiguration
{
    private static Logger log = LoggerFactory.getLogger(SystemConfiguration.class);
 
    private static SystemConfiguration systemConfiguration = new SystemConfiguration();
 
    private static List<String> locations;
 
    private SystemConfiguration()
    {
 
    }
 
    public static SystemConfiguration getInstance()
    {
        if (!isRead) {
            reload();
            isRead = true;
        }
        return systemConfiguration;
    }
 
    /**
     * 重新加载配置文件
     */
    public static void reload()
    {
        if (locations == null) {
            log.warn("没有配置文件,无法读取");
            return;
        }
        //预先清空原先的配置集合
        compositeConfiguration.clear();
        Configuration conf = null;
        int index = 0;
        int count = 0;
 
        for (String location : locations) {
            if (StringUtil.isValid(location)) {
                try {
                    log.debug("开始读取系统配置文件[{}]", location);
 
                    if (location.toLowerCase().endsWith(".xml")) {
                        conf = new XMLConfiguration(location);
                    }
                    else {
                        conf = new PropertiesConfiguration(location);
                    }
 
                    compositeConfiguration.addConfiguration(conf);
                    index = 0;
                    for (Iterator<String> it = conf.getKeys(); it.hasNext(); ) {
                        index++;
                        count++;
                        String key = it.next();
                        log.debug("配置文件信息:[key = {} , value = {} ]", key, conf.getString(key));
                    }
                    log.info("【{}】配置文件完毕,SystemConfig总共加载了 {} 个配置信息", location, index);
                }
                catch (ConfigurationException e) {
                    log.error("SystemConfiguration读取系统配置出现错误:", e);
                }
            }
        }
 
        log.info("所有配置文件完毕,systemConfiguration总共加载了 {} 个配置信息", count);
    }
 
 
    private static CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
 
    private static boolean isRead = false;
 
    /**
     * 读取key,返回boolean结果,如果没有找到对应键值,则返回false
     * @param key   键
     * @return boolean结果
     */
    public static boolean getBoolean(String key)
    {
        return getBoolean(key, false);
    }
 
    /**
     * 读取key,返回boolean结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return boolean结果
     */
    public static boolean getBoolean(String key, boolean defaultValue)
    {
        return compositeConfiguration.getBoolean(key, defaultValue);
    }
 
    /**
     * 读取key,返回字符串结果,如果没有找到对应键值,则返回null
     * @param key   键
     * @return 键值字符串
     */
    public static String getString(String key)
    {
        return getString(key, null);
    }
 
    /**
     * 读取key,返回字符串结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值字符串
     */
    public static String getString(String key, String defaultValue)
    {
        return compositeConfiguration.getString(key, defaultValue);
    }
 
    /**
     * 读取key,返回int结果,如果没有找到对应键值,则返回0
     * @param key   键
     * @return 键值
     */
    public static int getInt(String key)
    {
        return getInt(key, 0);
    }
 
    /**
     * 读取key,返回int结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值
     */
    public static int getInt(String key, int defaultValue)
    {
        return compositeConfiguration.getInt(key, defaultValue);
    }
 
    /**
     * 读取key,返回double结果,如果没有找到对应键值,则返回0f
     * @param key   键
     * @return 键值
     */
    public static double getDouble(String key)
    {
        return getDouble(key, 0d);
    }
 
    /**
     * 读取key,返回double结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值
     */
    public static double getDouble(String key, double defaultValue)
    {
        return compositeConfiguration.getDouble(key, defaultValue);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回0
     * @param key   键
     * @return 键值
     */
    public static byte getByte(String key)
    {
        return getByte(key, (byte) 0);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值
     */
    public static byte getByte(String key, byte defaultValue)
    {
 
        return compositeConfiguration.getByte(key, defaultValue);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回0f
     * @param key   键
     * @return 键值
     */
    public static float getFloat(String key)
    {
        return getFloat(key, 0f);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值
     */
    public static float getFloat(String key, float defaultValue)
    {
        return compositeConfiguration.getFloat(key, defaultValue);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回0l
     * @param key   键
     * @return 键值
     */
    public static long getLong(String key)
    {
        return getLong(key, 0l);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值
     */
    public static long getLong(String key, long defaultValue)
    {
        return compositeConfiguration.getLong(key, defaultValue);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回0
     * @param key   键
     * @return 键值
     */
    public static short getShort(String key)
    {
        return getShort(key, (short) 0);
    }
 
    /**
     * 读取key,返回key结果,如果没有找到对应键值,则返回默认值
     * @param key   键
     * @param defaultValue  默认值
     * @return 键值
     */
    public static short getShort(String key, short defaultValue)
    {
        return compositeConfiguration.getShort(key, defaultValue);
    }
 
    public List<String> getLocations()
    {
        return locations;
    }
 
    public void setLocations(List<String> locations)
    {
        this.locations = locations;
    }
}

    我根据commons-configuration组件特性,将配置文件读取格式可以读properties之外,也可以同时读取xml格式。这个工具类属于单例模式,也就是可以随时共享给jvm任何对象使用,在spring容器下,只需将配置文件指定好就可以完成配置文件自动读取,spring配置如下: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
  <bean id="systemConfiguration" class="com.zjhcsoft.modules.configuration.SystemConfiguration" init-method="getInstance">
    <property name="locations">
      <list>
        <value>test.properties</value>
        <value>test.xml</value>
      </list>
    </property>
  </bean>
</beans>



     容器对象只需要在初始化时调用SystemConfiguration类的getInstance来获取单例对象即可。然后将配置文件注入到locations成员属性即可。我们在使用时无需在初始化该对象,即可立即取出配置文件中预设值。下面我举个例子,准备test.properies配置文件和test.xml配置文件。

test.properies

abc=123
tiwen=hello!tiwen


test.xml

<?xml version="1.0" encoding="UTF-8"?>
<conf>
  <node1>true</node1>
  <node2>10000</node2>
</conf>

 

java测试例子如下:

/**
 * Copyright(c) 2005 zjhcsoft Techonologies, Ltd.
 *
 * History:
 *   2010-3-4 14:10:33 Created by Tiwen
 */
package com.zjhcsoft.modules.configuration;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 
/**
 * 系统配置文件参获取类
 *
 * @author <a href="mailto:Tiwen@qq.com">Tiwen</a>
 * @version 1.0 2010-3-4 14:10:33
 */
public class SystemConfigurationTest
{
    public  static void main(String []args){
    ApplicationContext ctx = new ClassPathXmlApplicationContext("modules.xml");
    System.out.println("properties config. key tiwen=" + SystemConfiguration.getString("tiwen"));
    System.out.println("properties config. key abc=" + SystemConfiguration.getString("abc"));
   
    System.out.println("xml config. key node1=" + SystemConfiguration.getBoolean("node1"));
    System.out.println("xml config. key node2=" + SystemConfiguration.getInt("node2"));
    }
}



打印结果如下: 

properties config. key tiwen=hello!tiwen
properties config. key abc=123
xml config. key node1=true
xml config. key node2=10000


很简单吧,SystemConfiguration类还提供多种数据类型转换接口,大家根据自己需要进行选择,但记住,转换类一定要对应正确的配置值,如“123”不可以使用getBoolean方法,否则会报出类型转换错误运行时异常。 


工具类完整代码下载地址:http://download.csdn.net/detail/tiwen818/3873255


原创文章,如果转载,请标注作者:田文  CSDN地址:http://blog.csdn.net/tiwen818

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值