属性集 Properties
java.util.Properties 继承于 Hashtable<K,V> ,来表示一个持久的属性集,可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串 。
- 是一个双列集合,K和V默认都是字符串,所以不用写泛型了
- 该类也被许多Java类使用,比如获取系统属性时,
System.getProperties 方法就是返回一个Properties对象。
- Properties 集合是一个唯一和IO流相结合的集合
- 方法store,把集合中的临时数据,持久化写入到硬盘中存储
- 方法load,把硬盘中保存的文件(键值对),读取到集合中使用
一些操作字符串的特有方法
Object setProperty(String key, String value) :调用 Hashtable 的方法 put
String getProperty(String key) :用指定的键在此属性列表中搜索属性,此方法相当于Map集合中的get(key)方法
Set<String> stringPropertyNames() :返回此属性列表中的键集,其中该键及其对应值是字符串,此方法相当于Map集合中的keySet方法。
public class Demo {
public static void main(String[] args) throws IOException {
Properties prop=new Properties();
//添加数据,只能是字符串类型
prop.setProperty("aaa","111");
prop.setProperty("bbb","222");
prop.setProperty("ccc","333");
//使用stringPropertyNames把集合中的键取出,存储到一个set集合中
Set<String> set = prop.stringPropertyNames();
//遍历set集合
for (String key : set) {
String value = prop.getProperty(key);
System.out.println(key+","+value);
}
}
}
//结果
//bbb,222
//aaa,111
//ccc,333
store方法:把集合的临时数据持久化写入到硬盘中存储
void store(OutputStream out, String comments) :以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。
void store(Writer writer, String comments) :以适合使用load(Reader)方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
- 参数:
- OutputStream out:字节输出流,不能写中文
- Writer writer:字符输出流,可以写中文
- String comments:注释,用来解释说明保存的文件是做什么用的,不能使用中文,会产生乱码,默认是Unicode编码,一般使用空字符串“ ”
- 使用步骤:
- 创建Properties 集合对象,添加数据
- 传教字节输出流/字符输出流对象,构造方法中要绑定要输出的目的地
- 使用store方法,把集合中的临时数据,持久化写入硬盘中
- 释放资源
public class Demo02 {
public static void main(String[] args) throws IOException {
Properties prop=new Properties();
//添加数据,只能是字符串类型
prop.setProperty("aaa","111");
prop.setProperty("bbb","222");
prop.setProperty("ccc","333");
FileWriter fw=new FileWriter("D:\\document\\code\\xuexi\\java\\aaa\\a.txt");
prop.store(fw,"save data");
fw.close();
}
}
a.txt:
#save data
#Tue Jan 05 22:56:23 GMT+08:00 2021
bbb=222
aaa=111
ccc=333
load方法:把硬盘中保存的文件(键值对)读取到集合中使用
void load(InputStream inStream) :从输入流中读取属性列表(键和元素对)。
void load(Reader reader) :按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
- 参数
- InputStream inStream:字节输入流,不能读取含有中文的键值对
- Reader reader:字符输入流,能读取含有中文的键值对
- 使用步骤:
- 创建Properties 集合对象
- 使用load方法读取保存键值对的文件
- 遍历Properties 集合
- 注意
- 存储键值对的文件中,键与值默认的链接符号可以使用=、空格(或其他符号)
- 存储键值对的文件总,可以使用#进行注释,被注释的键值对不会再被读取
- 存储键值对的文件中,键与值默认都是字符串,不用再加引号
a.txt文件
#save data
#Wed Jan 06 17:26:02 GMT+08:00 2021
bbb 222
aaa=111
ccc=333
嘿嘿=诶哟
public class Demo {
public static void main(String[] args) throws IOException {
Properties prop=new Properties();
prop.load(new FileReader("D:\\document\\code\\xuexi\\java\\aaa\\a.txt"));
Set<String> set = prop.stringPropertyNames();
for (String key : set) {
String value = prop.getProperty(key);
System.out.println(key+"-"+value);
}
}
}
//结果
//嘿嘿-诶哟
//bbb-222
//aaa-111
//ccc-333