获取Properties配置文件中的值详解

我们知道,在做项目时,为了提高项目的扩展性是不能将参数写死的,所以,将值写入属性文件、xml文件等就成为了必然。那我们应该怎么获取当中的值呢?这个问题以前一直困恼着我,当然,那是很久以前的事情啦。我也相信肯定有很多人是不知道的,现在,我就分享一下我的写法吧:

1、在定义类的相关成员变量,如下:

public  static Properties config      =   new Properties();
private static String     config_path =  "fileUpload.properties";
private static Hashtable<String, Properties> instanceCache  = new Hashtable<String, Properties>();
2、创建两个方法,一个为获取属性文件的对象,另一个为加载属性文件的对象,分别如下:

        /**
	 * 加载配置文件
	 * @return 
	 */
	public Properties loadConfig(String propName){
		 InputStream in = getClass().getClassLoader().getResourceAsStream(config_path); 
		 try {
			config.load(in);
			instanceCache.put(propName, config);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return config;
	}
	
	/**
	 * 获取配置文件
	 * @param propFileName
	 * @return
	 */
	private static Properties getProperty(String propFileName) {
        if (instanceCache.containsKey(propFileName)) {
            return (Properties) instanceCache.get(propFileName);
        } else {
            return null;
        }
    }
3、编写主函数,对属性文件进行判断,如下:

        Properties config = getProperty(config_path);
        if (config == null) {
            config = loadConfig(config_path);
        }
4、通过属性文件中的name获取相应的value,如下:

       String tempDir = config.getProperty("tempDir");//存储图片的临时目录
OK,大功告成,有兴趣的童鞋自己动手试试吧!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值