properties的概述和作为map的使用
properties(常用来做配置文件):是一个双列集合,properties类表示了一个持久的属性集,可保存在流中或从流中加载,属性列表中每个键及其对应值都是一个字符串,是Hashtable的子类
(1)作为Map集合的使用
(2)其他功能的使用
public Object setProperty(String key,String value):设置键和值
public String getProperty(String key):根据键获取值
public Enumeration<String> stringPropertyNames():迭代,拿到所有键,存取到枚举,然后遍历
load()和store()方法
package pra_19;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
public class J_37 {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop=new Properties();
prop.put("a", 11);
System.out.println(prop); //{a=11},作为Map集合的使用
//特殊功能的使用
Properties prop2=new Properties();
prop2.setProperty("na", "kk");
prop2.setProperty("te", "123");
System.out.println(prop2);
Enumeration<String> en=(Enumeration<String>)prop2.propertyNames();
while(en.hasMoreElements()){
String key=en.nextElement(); //获取Properties中的每一个键
System.out.println(key);
String value=prop2.getProperty(key);//根据键获取值
System.out.println(value);
//做配置文件,通过IO流关联,使用load()和store()方法
Properties prop3=new Properties();
prop3.load(new FileInputStream("config.properties")); //将文件上的键值对读取到集合中
System.out.println(prop3);
prop3.setProperty("age","20"); //对其修改
System.out.println(prop3);
prop3.store(new FileOutputStream("config.properties"), "xxx"); //对其修改后写入配置文件,第二个参数是对列表参数的描述,也可以给null
}
}
}