1.概述
-
Properties
是Hashtable<k,v>
的子类,Hashtable<k,v>
是Map<k,v>
接口的实现类
Properties extends Hashtable<k.v> implements Map<k,v>
-
Properties
类表示了一个持久的属性集。Properties
可保存在流中或从流中加载。
●Properties
集合是唯一一个和IO流结合的集合
●store()
方法,把集合中的临时数据,持久化写入到硬盘中
●load()
方法,把硬盘中保存的文件(键值对),读取到集合中使用 -
Properties
集合是一个双列集合,键和值默认都是字符串
2.常用专属方法
1.添加数据
对象.setProperty(String key,String value)
2.通过键找到值
对象.getProperty(String key)
3.把Properties
集合中的键取出,放入到一个set
集合中
Set<String> set = 对象.stringPropertyNames();
3.store
方法
store(OutputStream out,String comments)
store(Writer writer,String comments)
OutputStream out 输出字节流,不能写入中文
Writer writer 输出字符流,可以写中文
String comments 注释,用来解释保存的文件是干什么用的,不能使用中文,一般使用""
(空字符串)
- 使用步骤
- 创建
Properties
集合对象,添加数据 - 创建字节/字符输出流对象,构造方法中绑定输出的目的地
- 使用
store()
方法,把集合中的临时数据,持久化的写入到硬盘 - 释放资源
package Demo01;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;
public class Demo01 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
FileWriter writer = new FileWriter("G:\\Java\\测试文件夹\\a.txt");
properties.setProperty("1","张三");
properties.setProperty("2","李四");
properties.setProperty("3","王五");
properties.setProperty("4","赵六");
properties.store(writer,"save data");
writer.close();
}
}
4.load
方法
load(InputStream out);
load(Reader reader);
OutputStream out 字节输入流,不能读含有中文的键值对
Reader reader 字符输入流,能读含有中文的键值对
- 使用步骤
- 创建
Properties
集合对象 - 使用
load()
方法,读取键值对文件 - 遍历
Properties
集合
- 注意
- 键值对文件中,键与值默认连接符为=,空格,或者其他
- 键值对文件中,可以使用#注释,被注释以后不会被读取
- 键值对文件中,键与值默认都是字符串
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class Demo02 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileReader("G:\\Java\\测试文件夹\\b.txt"));
for (String i:properties.stringPropertyNames()){
System.out.println(properties.get(i));
}
}
}