java.util.Properties集合 extends Hashtable <K,V> implements Map<K,V>
Properties
类表示一组持久的属性。 Properties
可以保存到流中或从流中加载。
Properties集合是唯一一个和IO流相结合的集合
void | load(InputStream inStream) | 从输入字节流读取属性列表(键和元素对)。 |
---|
void | store(OutputStream out, String comments) | 将此 |
---|
可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
可以使用Properties集合中的方法load,把硬盘中保存的文件(键值对),读取到集合中使用
属性列表中的每个键及其对应的值都是一个字符串
Properties集合是一个双列集合,key和value默认都是字符串 Properties集合有一些操作字符串的特有方法 Object setProperty(String key, String value) 调用 Hashtable方法 put 。
String getProperty(String key) 使用此属性列表中指定的键搜索属性。(通过key找到value值) 此方法相当于Map集合中的get(key)
Set<String> stringPropertyNames() 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。 返回的就是保存字符串的集合,此方法相当于Map集合中的keySet方法
Properties的构造方法
Properties() | 创建一个没有默认值的空属性列表。 |
---|---|
Properties(Properties defaults) | 创建具有指定默认值的空属性列表。 |
package com.baidu.属性集;
import java.util.Properties;
import java.util.Set;
public class 属性Properties {
public static void main(String[] args) {
show();
}
/*
使用Properties集合存储数据,遍历取出Properties集合中的数据
Properties集合是一个双列集合,key和value默认都是字符串
Properties集合有一些操作字符串的特有方法
Object setProperty(String key, String value) 调用 Hashtable方法 put 。
String getProperty(String key) 使用此属性列表中指定的键搜索属性。(通过key找到value值)
此方法相当于Map集合中的get(key)
Set<String> stringPropertyNames() 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。
返回的就是保存字符串的集合,此方法相当于Map集合中的keySet方法
*/
private static void show() {
//创建一个Properties集合对象
Properties prop = new Properties();
//使用setroperty往集合中添加数据
prop.setProperty("菠萝吹雪","180");
prop.setProperty("上官子怡","170");
prop.setProperty("电灯泡","2000");
//使用StringPropertyNames方法把properties集合中的键取出,存储到一个set集合中
//返回的就是一个set集合,集合里面的键默认就是字符串类型
Set<String> set = prop.stringPropertyNames();
//遍历set集合,取出Properties
for (String key : set) {
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
}
菠萝吹雪=180
上官子怡=170
电能泡=2000