java读取配置文件(Properties)

本文介绍了一个用于Java项目的属性文件操作工具类,该工具类提供了一系列的方法来读取、更新和保存properties文件。
package com.online.college.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {

    private static Map<String,Properties> propMap = new HashMap<String,Properties>();

    /*设置默认的properties文件,方便操作*/
    public static final String DEFAULT_PROPERTIES_FILE="application.properties";

    public static Object getProperty(String file,String key){
        Properties prop = getProperties(file);
        if(prop != null && prop.get(key) != null){
            return prop.get(key);
        }
        return null;
    }

    public static Properties getProperties(String file){
        try {
            if(propMap.get(file) == null){
                Properties prop = new Properties();
                prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(file));
                propMap.put(file,prop);
                return prop;
            }else{
                return propMap.get(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void updateProperties(Properties prop,String filePath){

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            URI fileUri = PropertiesUtil.class.getClassLoader().getResource(filePath).toURI();
            File file = new File(fileUri);

            Properties tmpProp = new Properties();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            tmpProp.load(bis);

            FileOutputStream fos = new FileOutputStream(file);
            for(Object key : prop.keySet()){
                tmpProp.setProperty(String.valueOf(key),String.valueOf(prop.get(key)));
            }
            tmpProp.store(fos, null);
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从默认配置文件中获取properties
     * @return
     */
    public static Properties getDefaultProperties(){
        return getProperties(DEFAULT_PROPERTIES_FILE);
    }

    /**
     * 从默认配置文件中获取配置项
     * @param key
     * @return
     */
    public static String getProperty(String key){
        Properties prop = getDefaultProperties();
        if(prop != null && prop.get(key) != null){
            return prop.getProperty(key);
        }
        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值