Properties集合的使用

Properties集合是唯一一个可以和IO流相结合的集合
可以将集合中的数据持久化存储,也可以将硬盘上的数据加载到该集合中。

1 Properties集合添加、遍历

 1 private static void show01() {
 2         // setProperty() 通过该方法向Properties内添加一对字符串键值对
 3         Properties properties = new Properties();
 4         properties.setProperty("kelvin", "180");
 5         properties.setProperty("jack", "168");
 6         properties.setProperty("siri", "170");
 7 
 8         // stringPropertyNames() 通过该方法获取Properties集合内的所有键组成的set集合
 9         Set<String> strings = properties.stringPropertyNames();
10         for (String key : strings) {
11             String value = properties.getProperty(key);
12             System.out.println(key + "--" + value);
13         }
14     }

2 Properties的store()方法持久化集合数据

 1 // store() 持久化数据
 2     private static void show02() throws IOException {
 3         /*
 4         持久化数据步骤:
 5          1 创建Properties对象,存储数据
 6          2 创建字节输出流/字符输出流对象,指定将数据持久化的位置(字节流不能持久化中文)
 7          3 调用Properties对象的save()方法,将集合中的临时数据持久化到指定位置
 8          4 释放资源
 9         */
10         Properties properties = new Properties();
11         properties.setProperty("kelvin", "180");
12         properties.setProperty("jack", "168");
13         properties.setProperty("siri", "170");
14 
15         FileWriter fw = new FileWriter("prop.txt");
16         properties.store(fw, "store data");
17         fw.close();
18     }

3 Properties 的load()方法加载文件数据到集合

 1      /*
 2         加载数据步骤:
 3              1 创建Properties对象
 4              2 调用load方法加载指定文件
 5              3 遍历Properties集合
 6         注意事项:
 7             1 存储键值对的文件中,可以使用=,空格或其他符号进行连接
 8             2 存储键值对的文件中,可以使用#进行注释,注释内容不会加载
 9             3 读取内容默认是字符串格式
10         */
11     private static void show03() throws IOException {
12         Properties properties = new Properties();
13         properties.load(new FileReader("prop.txt"));
14         Set<String> strings = properties.stringPropertyNames();
15         for (String key : strings) {
16             String value = properties.getProperty(key);
17             System.out.println(key + "--" + value);
18         }
19 
20     }    

# 注:在load或store方法中使用字节流或字符流的匿名对象无需释放资源。

原文地址:https://www.cnblogs.com/sun-10387834/p/13518215.html