【java学习笔记】Properties

时间:2022-04-14 17:55:58

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

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

1.写properties文件

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

student.properties:

【java学习笔记】Properties

2.读properties文件

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

结果:

【java学习笔记】Properties

3.properties的用处

path=D:\\a.txt
----->进行更改--->
path=D:\\b.txt

config.properties

 import java.io.FileInputStream;
import java.util.Properties; public class PropertiesDemo3 {
public static void main(String[] args) throws Exception {
// 创建properties对象
Properties prop = new Properties();
while (true) {
// 加载properties文件
prop.load(new FileInputStream("config.properties"));
// 读取文件
FileInputStream fin = new FileInputStream(prop.getProperty("path"));
byte[] bs = new byte[10];
int len = -1;
while ((len = fin.read(bs)) != -1) {
System.out.println(new String(bs, 0, len));
}
fin.close();
Thread.sleep(3000);
}
}
}

结果:

【java学习笔记】Properties