加入收藏 | 设为首页 | 会员中心 | 我要投稿 辽源站长网 (https://www.0437zz.com/)- 云专线、云连接、智能数据、边缘计算、数据安全!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

深入浅出的分析 Properties

发布时间:2019-11-12 14:17:08 所属栏目:优化 来源:炸鸡可乐
导读:最近在看 java 集合源码的时候,发现原来我们经常使用的 Properties 类既然继承自 Hashtable!又涨见识了! 01. 摘要 在集合系列的第一章,咱们了解到,Map 的实现类有 HashMap、LinkedHashMap、TreeMap、IdentityHashMap、WeakHashMap、Hashtable、Properti

enumerate 方法,源码如下:

  1. private synchronized void enumerate(Hashtable<String,Object> h) { 
  2.     //判断 Properties 中是否有初始化的配置文件 
  3.     if (defaults != null) { 
  4.         defaults.enumerate(h); 
  5.     } 
  6.     //将原 Hashtable 中的数据添加到新的 Hashtable 中 
  7.     for (Enumeration<?> e = keys() ; e.hasMoreElements() ;) { 
  8.         String key = (String)e.nextElement(); 
  9.         h.put(key, get(key)); 
  10.     } 

方法测试如下:

  1. public static void main(String[] args) throws Exception { 
  2.     //初始化 Properties 
  3.     Properties prop = new Properties(); 
  4.     //加载配置文件 
  5.     InputStream in = TestProperties.class.getClassLoader().getResourceAsStream("custom.properties"); 
  6.     //读取配置文件,指定读取编码 UTF-8,防止内容乱码 
  7.     prop.load(new InputStreamReader(in, "UTF-8")); 
  8.     //获取 Properties 中全部的 key 元素 
  9.     Enumeration enProp = prop.propertyNames(); 
  10.     while (enProp.hasMoreElements()){ 
  11.         String key = (String) enProp.nextElement(); 
  12.         String value = prop.getProperty(key); 
  13.         System.out.println(key + "=" + value); 
  14.     } 

输出内容如下:

userPwd=123456

userEmail=123@123.com

userAge=18

userName=李三

userGender=男

总结

Properties 继承自 Hashtable,大部分方法都复用于 Hashtable,比如,get、put、remove、clear 方法,**与 Hashtable 不同的是, Properties中的 key 和 value 都是字符串,**如果需要获取 properties 中全部内容,可以先通过迭代器或者 propertyNames 方法获取 map 中所有的 key 元素,然后遍历获取 key 和 value。

需要注意的是,Properties 中的 setProperty 、load 方法,都加了synchronized同步锁,用来控制线程同步。

03. properties 文件的加载方式

在实际开发中,经常会遇到读取配置文件路径找不到,或者读取文件内容乱码的问题,下面简单介绍一下,properties 文件的几种常用的加载方式。

properties 加载文件的方式,大致可以分两类,第一类是使用 java.util.Properties 的 load 方法来加载文件流;第二类是使用 java.util.ResourceBundle 类来获取文件内容。

在src/recources目录下,新建一个custom.properties配置文件,文件编码格式为UTF-8,内容还是以刚刚那个测试为例,各个加载方式如下!

通过文件路径来加载文件

这类方法加载文件,主要是调用 Properties 的 load 方法,获取文件路径,读取文件以流的形式加载文件。

方法如下:

  1. Properties prop = new Properties(); 
  2. //获取文件绝对路径 
  3. String filePath = "/coding/java/src/resources/custom.properties"; 
  4. //加载配置文件 
  5. InputStream in = new FileInputStream(new File(filePath)); 
  6. //读取配置文件 
  7. prop.load(new InputStreamReader(in, "UTF-8")); 
  8. System.out.println("userName:"+prop.getProperty("userName")); 

输出结果:

userName:李三 

通过当前类加载器的getResourceAsStream方法获取

这类方法加载文件,也是调用 Properties 的 load 方法,不同的是,通过类加载器来获取文件路径,如果当前文件是在src/resources目录下,那么直接传入文件名就可以了。

(编辑:辽源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读