Properties配置文件

 1 package file;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.FileReader;
 5 import java.io.FileWriter;
 6 import java.io.IOException;
 7 import java.util.Map.Entry;
 8 import java.util.Properties;
 9 import java.util.Set;
10 
11 /*
12  Properties(配置文件类 )
13      1.如果配置文件的信息出现了中文,只能使用字符解决,如果使用字节流,默认是ISO8859-1,会出现乱码。
14       2.如果Properties中的内容发生了变化,一定要重新存储这个配置文件.
15  */
16 public class Demo11 {
17     public static void main(String[] args) throws IOException {
18 //        createProperties();
19         readProperties();
20     }
21     
22     
23     //读取配置文件信息
24     public static void readProperties() throws IOException {
25         //创建Properties
26         Properties properties = new Properties();
27         //加载配置文件到properties中,
28         properties.load(new FileReader("F:\test.properties"));
29         //遍历Properties
30         Set<Entry<Object, Object>> entrys = properties.entrySet();
31         for(Entry<Object,Object> enrty : entrys) {
32             System.out.println("键:"+ enrty.getKey() + "值:" + enrty.getValue());
33         }
34         
35         //修改密码
36         properties.setProperty("测试", "888");
37         //重新把修改后的信息properties,在生成一个配置文件
38         properties.store(new FileWriter("F:\test.properties"), "he");
39     }
40     
41     //保存配置文件的信息
42     public static void createProperties() throws IOException, IOException {
43         //创建Properties
44         Properties properties = new Properties();
45         properties.setProperty("测试", "123");
46         properties.setProperty("测试2", "234");
47         properties.setProperty("测试3", "456");
48         
49         //遍历Properties
50 //        Set<Entry<Object, Object>> entrys = properties.entrySet();
51 //        for(Entry<Object,Object> enrty : entrys) {
52 //            System.out.println("键:"+ enrty.getKey() + "值:" + enrty.getValue());
53 //        }
54         
55         //使用properties产生配置文件
56 //        properties.store(new FileOutputStream("F:\test.properties"), "ha");    //第一个是输出流对象,第二个是描述信息
57         properties.store(new FileWriter("F:\test.properties"), "he");
58         
59     }
60     
61 }
原文地址:https://www.cnblogs.com/linst/p/5666698.html