30 多份配置文件合并功能

maven 依赖

 <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.6</version>
        </dependency>

代码

package com.da.tool.util.configuration;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 */
public class ConfigParser {
    public static void main(String[] args) throws IOException, ConfigurationException {
        //配置项  分为默认配置 和用户配置
        //用户配置会覆盖默认配置   下面为类支持

        CompositeConfiguration allConfig = new CompositeConfiguration();

        Properties defaultProp=new Properties();
        defaultProp.put("A","1");
        defaultProp.put("B","2");

        defaultProp.store(new FileOutputStream("defaultProp.properties"),"defaultProp");

        PropertiesConfiguration defaultConfig=new PropertiesConfiguration();
        defaultConfig.load(new FileInputStream("defaultProp.properties"));

        Properties userProp=new Properties();
        userProp.put("A","10");
        userProp.store(new FileOutputStream("userProp.properties"),"userProp");

        PropertiesConfiguration userConfig=new PropertiesConfiguration();
        userConfig.load(new FileInputStream("userProp.properties"));

        allConfig.addConfiguration(userConfig);  //两个配置文件中相同的key  先加入的生效
        allConfig.addConfiguration(defaultConfig);

        System.out.println("A = " + allConfig.getString("A"));
        System.out.println("B = " + allConfig.getString("B"));

    }
}

 

posted @ 2017-01-23 10:56  life_start  阅读(367)  评论(0编辑  收藏  举报