属性集合java.util.Properties
java.util.Properties集合 extends Hashtable<k, v> implements Map<k, v>
Properties类表示一个持久的属性集,可以保存在流中,或者从流中加载。是唯一一个和IO流相结合的集合。Properties集合是一个双列集合,key和value默认都是字符串
方法
方法 | 作用 |
---|---|
void store(OutputStream out, String comments) | 把集合的临时数据,持久化写到硬盘存储 |
void load(Writer writer, String comments) | 把硬盘的文件(键值对),读取到集合中使用 |
store方法使用步骤
- 创建Properties对象,添加数据
- 创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
- 使用properties对象的store方法,把集合的临时数据持久化写入到硬盘
- 释放资源
package cn.zhuobo.day14.aboutProperties;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class Demo01Properties {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("aaa","11");
properties.setProperty("bbb", "22");
properties.setProperty("ccc", "33");
// 使用字符输出流
FileWriter fw = new FileWriter("/home/zhuobo/Desktop/dir/prop.txt");
properties.store(fw, "store data");
// 使用字节输出流的匿名对象
properties.store(new FileOutputStream("/home/zhuobo/Desktop/dir/prop1.txt"), "");
Set<String> keySet = properties.stringPropertyNames();
for (String key : keySet) {
System.out.println(properties.getProperty(key));
}
fw.close();
}
}
键值对写入文件,键与值之间使用空格分隔也是和等号一样的效果,#后面的是注释
load方法使用
- 创建Properties对象
- 使用Properties对象的load方法读取保存键值对的文件
- 遍历Properties集合查看
// 创建Properties对象
Properties properties1 = new Properties();
// 使用Properties对象的load方法读取保存键值对的文件
properties1.load(new FileReader("/home/zhuobo/Desktop/dir/prop1.txt"));
// 遍历Properties集合查看
Set<String> keySet = properties.stringPropertyNames();
for (String key : keySet) {
System.out.println(key + "=" + properties.getProperty(key));
}
该集合有些特有的处理字符串的方法:
方法 | 作用 |
---|---|
Object setProperty(String key, String value) | 调用Hashtable的put方法 |
String getProperty(String key) | 相当于Map中的get方法,通过键获得值 |
Set |
返回此属性列表的键值,其中该键值对应值都是字符串,此方法相当于Map集合的keySet方法 |
package cn.zhuobo.day14.aboutProperties;
import java.util.Properties;
import java.util.Set;
// 注意使用Properties集合特有的处理字符串的方法
public class Demo01Properties {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("aaa","11");
properties.setProperty("bbb", "22");
properties.setProperty("ccc", "33");
Set<String> keySet = properties.stringPropertyNames();
for (String key : keySet) {
System.out.println(properties.getProperty(key));
}
*