1,Properties的概述
-
Properties 类表示了一个持久的属性集。
-
Properties 可保存在流中或从流中加载。
-
属性列表中每个键及其对应值都是一个字符串。
-
Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。
2,简单使用:
-
Properties作为Map集合的使用
public static void demo1() {
Properties prop = new Properties();
prop.put("abc", 123);
System.out.println(prop);
}
3,Properties的特殊功能
-
public Object setProperty(String key,String value) 设置键设置值
-
public String getProperty(String key) 获取值。
-
public Enumeration<String> stringPropertyNames() 获取每一个键
【1】 Properties的特殊功能
public static void demo2() {
Properties prop = new Properties();
prop.setProperty("name", "张三");
prop.setProperty("tel", "18912345678");
//System.out.println(prop);
Enumeration<String> en = (Enumeration<String>) prop.propertyNames();
while(en.hasMoreElements()) {
String key = en.nextElement(); //获取Properties中的每一个键
String value = prop.getProperty(key); //根据键获取值
System.out.println(key + "="+ value);
}
}
4,Properties的load()和store()功能
【1】Properties
-
load()功能 ,将文件上的键值读取到集合中
-
store()功能, 刷新数据存储
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties")); //将文件上的键值对读取到集合中
prop.setProperty("tel", "18912345678");
prop.store(new FileOutputStream("config.properties"), null);//第二个参数是对列表参数的描述,可以给值,也可以给null
System.out.println(prop);
}