读取配置文件简单帮助类

package com.demo.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;

/**
*
* 类: PropertiesUtil
* 描述: 读取配置文件
* 作者: xxx
* 版本: 1.0
* 时间: 2015-7-18 上午11:30:01
*/

public class PropertiesUtil {

    private ResourceBundle resourceBundle;
    private String Path;
    private Properties propertie;
    private InputStream inputStream;
    
    /*//不同包下通过Properties读取
    String  valueString1=new  PropertiesUtil("/com/demo/config/config.properties").getPropertyValue("username");
    System.out.println(valueString1);        
    //当前包下读取
    String  valueString2=new  PropertiesUtil("config.properties").getPropertyValue("username");
    System.out.println(valueString2);        

    String  valueString3=new  PropertiesUtil("com/demo/config/config",Locale.getDefault()).getProperty("username");
    System.out.println(valueString3);        */
    

    /**
     * Path文件路径
     * 
     * @param Path
     *            (Path示例:com/demo/config/config)
     */
    public PropertiesUtil(String Path, Locale Locale1) {
        this.resourceBundle = ResourceBundle.getBundle(Path,
                Locale1.getDefault());
    }

    /**
     * 
     * @param  Path1   (读取当前包下配置文件:config.properties)
     *                      Path2(读取不同包下配置文件:/com/demo/config/config.properties)
     */
    public PropertiesUtil(String Path) {

        this.Path = Path;
    }

    /**
     * 通过Properties方式读取 通过对应key获取相对应value值
     * 
     * @param key键值
     * @return value值
     */
    public String getPropertyValue(String key) {
        String result = "";
        try {
            if (key == null || "".equals(key) || "null".equals(key)) {
                return "";
            }
            propertie = new Properties();
            inputStream = PropertiesUtil.class.getResourceAsStream(Path);
            propertie.load(inputStream);
            inputStream.close();
            result = (String) propertie.getProperty(key);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 通过ResourceBundle方式读取 通过对应key获取相对应value值
     * 
     * @param key键值
     * @return value值
     */
    public String getProperty(String key) {
        if (key == null || "".equals(key) || "null".equals(key)) {
            return "";
        }
        String result = "";
        try {
            result = resourceBundle.getString(key);
        } catch (MissingResourceException e) {

            e.printStackTrace();
        }
        return result;
    }
}

 

转载于:https://www.cnblogs.com/BABLOVE/p/4656516.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值