enumerate 方法,源码如下:
- private synchronized void enumerate(Hashtable<String,Object> h) {
- //判断 Properties 中是否有初始化的配置文件
- if (defaults != null) {
- defaults.enumerate(h);
- }
- //将原 Hashtable 中的数据添加到新的 Hashtable 中
- for (Enumeration<?> e = keys() ; e.hasMoreElements() ;) {
- String key = (String)e.nextElement();
- h.put(key, get(key));
- }
- }
方法测试如下:
- public static void main(String[] args) throws Exception {
- //初始化 Properties
- Properties prop = new Properties();
- //加载配置文件
- InputStream in = TestProperties.class.getClassLoader().getResourceAsStream("custom.properties");
- //读取配置文件,指定读取编码 UTF-8,防止内容乱码
- prop.load(new InputStreamReader(in, "UTF-8"));
- //获取 Properties 中全部的 key 元素
- Enumeration enProp = prop.propertyNames();
- while (enProp.hasMoreElements()){
- String key = (String) enProp.nextElement();
- String value = prop.getProperty(key);
- System.out.println(key + "=" + value);
- }
- }
输出内容如下:
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 方法,获取文件路径,读取文件以流的形式加载文件。
方法如下:
- Properties prop = new Properties();
- //获取文件绝对路径
- String filePath = "/coding/java/src/resources/custom.properties";
- //加载配置文件
- InputStream in = new FileInputStream(new File(filePath));
- //读取配置文件
- prop.load(new InputStreamReader(in, "UTF-8"));
- System.out.println("userName:"+prop.getProperty("userName"));
输出结果:
userName:李三
通过当前类加载器的getResourceAsStream方法获取
这类方法加载文件,也是调用 Properties 的 load 方法,不同的是,通过类加载器来获取文件路径,如果当前文件是在src/resources目录下,那么直接传入文件名就可以了。 (编辑:站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|