【java学习笔记】Properties

Properties:可以持久化的映射,规定键和值的类型是String。

Properties对象必须放到.properties文件中,其中properties文件默认为西欧编码,也因此不存储中文。

1.写properties文件

 1 import java.io.FileOutputStream;
 2 import java.util.Properties;
 3 
 4 public class PropertiesDemo {
 5     public static void main(String[] args) throws Exception {
 6         // 创建一个properties对象
 7         Properties prop = new Properties();
 8         // 添加键值对:键和值的类型都是String
 9         prop.setProperty("name", "xs");
10         prop.setProperty("id", "666666");
11         prop.setProperty("gender", "f");
12         // 持久化
13         // Properties对象在序列化的时候必须放到properties文件中
14         // 第二个参数表示向properties文件中添加注释描述这个properties文件的作用
15         prop.store(new FileOutputStream("student.properties"), "this is a student");
16     }
17 }

student.properties:

2.读properties文件

 1 import java.io.FileInputStream;
 2 import java.util.Properties;
 3 public class PropertiesDemo2 {
 4     public static void main(String[] args) throws Exception {
 5         Properties prop = new Properties();
 6         // 读取properties文件
 7         prop.load(new FileInputStream("p.properties"));
 8         // 根据键获取值:如果键不存在,则返回一个null
 9         // 也可以指定默认值(如果没有对应的键,则返回默认值)
10         System.out.println(prop.getProperty("id"));
11         System.out.println(prop.getProperty("x"));
12         System.out.println(prop.getProperty("xxx", "x"));
13     }
14 }

结果:

    

3.properties的用处

path=D:\a.txt
----->进行更改--->
path=D:\b.txt
config.properties
 1 import java.io.FileInputStream;
 2 import java.util.Properties;
 3 
 4 public class PropertiesDemo3 {
 5     public static void main(String[] args) throws Exception {
 6         // 创建properties对象
 7         Properties prop = new Properties();
 8         while (true) {
 9             // 加载properties文件
10             prop.load(new FileInputStream("config.properties"));
11             // 读取文件
12             FileInputStream fin = new FileInputStream(prop.getProperty("path"));
13             byte[] bs = new byte[10];
14             int len = -1;
15             while ((len = fin.read(bs)) != -1) {
16                 System.out.println(new String(bs, 0, len));
17             }
18             fin.close();
19             Thread.sleep(3000);
20         }
21     }
22 }

结果:

原文地址:https://www.cnblogs.com/kuotian/p/8423454.html