Properties类

1、Properties类简介

Properties类表示一个持久化的属性集。Properties可保存在流中或从流中加载。属性表中每个键及其对应值都是一个字符串。

特点:

  • Hashtable的子类,map集合中的方法都可以用
  • 该集合没有泛型,键值都是字符串
  • 它是一个可以持久化的属性集。键值可以存储到集合中,也可以存储到持久化设备上。键值的来源也可以是持久化设备。

常用的和流技术相结合的方法:

void load(InputStream):把指定输入字节流所对应的文件中的数据,读取出来,保存到Properties集合中

void load(Reader):从指定的字符输入流中读取属性列表

void store(OutputStream out, String comments):把集合中的数据,保存到指定的流所对应的文件中

void store(Write write, String comments)

 1 package properties;
 2 
 3 import java.util.Properties;
 4 import java.util.Set;
 5 
 6 /**
 7  * <p>Description:Properties与流结合方法演示 </p>
 8  * @author Administrator
 9  * @date 2018年11月10日下午10:29:25
10  */
11 public class PropertiesDemo {
12 
13     public static void main(String[] args) {
14         // 创建Properties集合对象
15         Properties prop = new Properties();
16         // 向集合中添加元素
17         prop.setProperty("马云", "阿里巴巴");
18         prop.setProperty("李彦宏", "百度");
19         prop.setProperty("马化腾", "腾讯");
20         
21         // 遍历集合
22         Set<String> keys = prop.stringPropertyNames();
23         for (String key : keys) {
24             String value = prop.getProperty(key);
25             System.out.println(key + ":" + value);
26         }
27     }
28 
29 }

2、将集合中的内容存储到文件

 1 package properties;
 2 
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.util.Properties;
 6 
 7 /**
 8  * <p>Description:使用Properties集合将数据存储到文件 </p>
 9  * @author Administrator
10  * @date 2018年11月10日下午10:35:30
11  */
12 public class PropertiesDemo2 {
13 
14     public static void main(String[] args) throws IOException {
15         // 1、创建Properties集合对象
16         Properties prop = new Properties();
17         // 2、向集合中添加元素
18         prop.setProperty("马云", "阿里巴巴");
19         prop.setProperty("李彦宏", "百度");
20         prop.setProperty("马化腾", "腾讯");
21         // 3、创建流
22         FileWriter fw = new FileWriter("e:\javaIOTest\prop.properties");
23         // 4、把集合中的数据存储到流所对应的文件中
24         prop.store(fw, "sava data");
25         // 5、关闭资源
26         fw.close();
27     }
28 
29 }

3、读取文件中的数据

 1 package properties;
 2 
 3 import java.io.FileReader;
 4 import java.io.IOException;
 5 import java.util.Properties;
 6 
 7 /**
 8  * <p>Description:Properties读取文件数据演示 </p>
 9  * @author Administrator
10  * @date 2018年11月10日下午10:41:12
11  */
12 public class PropertiesDemo3 {
13 
14     public static void main(String[] args) throws IOException {
15         // 1、创建Properties集合对象
16         Properties prop = new Properties();
17         // 2、创建流对象
18         FileReader fr = new FileReader("e:\javaIOTest\prop.properties");
19         // 3、读取数据
20         prop.load(fr);
21         // 4、关闭资源
22         fr.close();
23         System.out.println(prop);
24     }
25 
26 }
原文地址:https://www.cnblogs.com/alphajuns/p/9940960.html