java.util.Properties集合 extends Hashtable<k,v> implements Map<k, v>
唯一和IO流结合的集合
可以使用Properties中store方法,把集合中的临时数据,持久化写入到硬盘中存储
使用Properties中load方法,把硬盘中保存的文件(键值对),读取到集合中使用
属性列表中每个键及其对应值都是一个字符串(泛型都是String)
Properties是一个双列集合,key和value默认都是字符串
public static void main(String[] args) {
show01();
}
private static void show01() {
Properties prop = new Properties();
prop.setProperty("cc", "168");
prop.setProperty("zz", "167");
prop.setProperty("qq", "166");
//相当于setKey,将所有的key值放入一个Set集合内
Set<String> set = prop.stringPropertyNames();
for (String s : set) {
System.out.println(s);
//相当于getKey获取到键对应的值
System.out.println(prop.getProperty(s));
}
}
字符流可以写中文,字节流不能写中文
store方法:
使用步骤:
- 创建Properties集合对象,添加数据
- 创建字节/字符输出流对象,构造方法中绑定要输出的目的地
- 使用Properties集合的store方法,把集合中的临时数据,持久化写入到硬盘中存储
- 释放资源
public static void main(String[] args) throws IOException {
show01();
show02();
}
private static void show02() throws IOException {
Properties prop = new Properties();
prop.setProperty("cc", "168");
prop.setProperty("zz", "167");
prop.setProperty("qq", "166");
FileWriter fw = new FileWriter("E:\\A JI\\program\\java\\f.txt");
prop.store(fw, "save data");
fw.close();
}
load方法:
使用步骤:
- 创建Properties集合对象
- 使用Properties集合的load方法读取保存键值对的文件
- 遍历Properties集合
注意:
- 存储键值对的文件中,键与值默认的连接符号可以使用=,空格(其他符号)
- 存储键值对的文件中,可使用#进行注释,被注释的键值不会被读取
- 存储键值对的文件中,键与值默认都是字符串,不用再加引号
public static void main(String[] args) throws IOException {
show03();
}
private static void show03() throws IOException {
Properties prop = new Properties();
prop.load(new FileReader("E:\\A JI\\program\\java\\f.txt"));
Set<String> set = prop.stringPropertyNames();
for (String s : set) {
System.out.println(s + "=" + prop.getProperty(s));
}
output:
cc=168
zz=167
qq=166
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。