第十八节——Properties集合

Properties集合学习

一、介绍

  1. 是一个Map体系的集合类
  2. Properties可以保存到流中或从流中加载
  3. 属性列表中的每个键及其对应的值都是一个字符串

二、Properties使用

  1. 创建:Properties pro = new Properties();
  2. Object setProperty(String key,String value):设置集合的键和值,都是String类型,底层调用 Hashtable方法put
  3. String getProperty(String key) :使用此属性列表中指定的键搜索属性
  4. Set stringPropertyNames():从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串
  5. 举例
Properties pro = new Properties();
pro.setProperty("123","qwe");
pro.setProperty("456","asd");
Set<String> set = pro.stringPropertyNames();
for(String s :set){
    
    
    System.out.println(pro.getProperty(s));
}

三、Properties和IO流相结合的方法

  1. void load(InputStream inStream):从输入字节流读取属性列表(键和元素对)
  2. void load(Reader reader) :从输入字符流读取属性列表(键和元素对)
  3. void store(OutputStream out, String comments):将此属性列表(键和元素对)写入此 Properties表中,以适合于使用load(InputStream)方法的格式写入输出字节流
  4. void store(Writer writer,String comments):将此属性列表(键和元素对)写入此 Properties表中,以适合使用load(Reader)方法的格式写入输出字符流
  5. 举例:
//store方法
Properties prop = new Properties();
prop.setProperty("itheima001","林青霞");
prop.setProperty("itheima002","张曼玉");
prop.setProperty("itheima003","王祖贤");
//void store(Writer writer, String comments):
FileWriter fw = new FileWriter("myOtherStream\\fw.txt");
prop.store(fw,null);
fw.close();
//load方法
Properties prop = new Properties();
//void load(Reader reader):
FileReader fr = new FileReader("myOtherStream\\fw.txt");
prop.load(fr);
fr.close();
System.out.println(prop)

猜你喜欢

转载自blog.csdn.net/qq_37589805/article/details/119580595