加载properties文件

加载properties文件的方式有两种:

  1、通过io流的方式来加载properties文件

 1 /**
 2      * 通过io流的方式来加载properties文件
 3      * 
 4      * @throws Exception
 5      */
 6     @Test
 7     public void test1() throws Exception {
 8         // 实例化Properties对象
 9         Properties p = new Properties();
10         // 通过load()方法加载properties文件,文件为绝对路径,且带有后缀
11         p.load(new FileReader("F:\java_oracle\day17\src\resource\data.properties"));
12         // 通过keySet()方法将所有的properties文件中的key值存放在一个set集合中
13         Set<Object> set = p.keySet();
14         // 迭代出每一个key值
15         Iterator<Object> it = set.iterator();
16         while (it.hasNext()) {
17             String key = (String) it.next();
18             // 通过Properties对象的getProperty(key)方法,得到value值
19             String value = p.getProperty(key);
20             System.out.println(key + "	" + value);
21         }
22     }

  2通过ResourceBundle来加载properties文件

 1 /**
 2      * 通过ResourceBundle来加载properties文件
 3      * 
 4      * @throws Exception
 5      */
 6     @Test
 7     public void test2() throws Exception {
 8         // 通过ResourceBundle类的getBundle()方法得到一个ResourceBundle对象
 9         ResourceBundle rb = ResourceBundle.getBundle("resource.data");
10         // 通过keySet()方法将所有的properties文件中的key值存放在一个set集合中
11         Set<String> set = rb.keySet();
12         Iterator<String> it = set.iterator();
13         while (it.hasNext()) {
14             String key = it.next();
15             // 通过ResourceBundle对象的getString(key)方法,得到value值
16             String value = rb.getString(key);
17             System.out.println(key + "	" + value);
18         }
19     }

  运行结果为:

 1 key4    d
 2 key3    c
 3 key6    aa
 4 key5    aa
 5 key2    b
 6 key1    a
 7 key10    c
 8 key11    c
 9 key8    b
10 key7    a
11 key9    c
原文地址:https://www.cnblogs.com/void0720/p/4778049.html