特点:
1,该集合的键和值都是字符串类型
2,该集合的数据可以保存在流中,或者从流获取
通常该集合用于操作以键值对形式存在的配置文件
public static void main(String[] args) throws IOException {
Properties p = new Properties();
p.setProperty("张三", "23");
p.setProperty("李四", "35");
p.setProperty("王五", "19");
p.setProperty("赵六", "22");
Set<String> names = p.stringPropertyNames();
for(String name : names){
String value = p.getProperty(name);
System.out.println(name+":"+value);
}
}
结果:
赵六:22
王五:19
张三:23
李四:35
list方法:
public static void main(String[] args) throws IOException {
Properties p = new Properties();
p.setProperty("张三", "23");
p.setProperty("李四", "35");
p.setProperty("王五", "19");
p.setProperty("赵六", "22");
// 将属性列表输出到指定的输出流。此方法对调试很有用。
p.list(System.out);
}
结果:
-- listing properties --
赵六=22
王五=19
张三=23
李四=35
store方法:
public static void main(String[] args) throws IOException {
Properties p = new Properties();
p.setProperty("张三", "23");
p.setProperty("李四", "35");
p.setProperty("王五", "19");
p.setProperty("赵六", "22");
//将集合数据持久化 保存在硬盘的文件中
// FileOutputStream fos = new FileOutputStream("C:\\Users\\悠悠华\\Desktop\\test\\ccc.txt");
//
// p.store(fos, "随便来一下");
FileWriter fw = new FileWriter("C:\\Users\\悠悠华\\Desktop\\test\\ccc.txt");
p.store(fw, "this is message");
}
结果:
修改配置信息
配置文件
public static void main(String[] args) throws IOException {
//新建一个文件对象
File file = new File("C:\\Users\\悠悠华\\Desktop\\test\\ccc.txt");
//新建一个输入流与文件对象相关联
FileInputStream fis = new FileInputStream(file);
//新建一个属性对象
Properties p = new Properties();
//先将文件对象的数据存入这个属性对象中
p.load(fis);
//先测试一下 属性对象的键值对有哪些
p.list(System.out);
//重新设置 this 键的值 将其改为 789
p.setProperty("this", "789");
//再次测试一下 属性对象的键值对有哪些
p.list(System.out);
//新建一个输出流
FileOutputStream fos = new FileOutputStream(file);
//将属性对象的键值对持久化 存储到文件中
p.store(fos, "heihei");
//关闭流
fis.close();
}
结果:
-- listing properties --
b=3
this=456
a=2
-- listing properties --
b=3
this=789
a=2