【 Properties 集合】 配置文件操作

java.util.Properties 集合 extends Hashtable<k,v>implements Map<k,v>
*         持久的属性集   Propertis可以保存在流中  或者从流中加载
*         唯一的一个和IO流相结合的集合
*         store 把流中临时的数据  持久化到硬盘中存储
*         load把硬盘中的文件(键值对) 读取到 集合中使用

 

一:使用properties集合存储数据,遍历出来
方法:

  1.propertes 集合有一些操作字符串的方法
  2.setProperties(String key,Strign value)
  3.getProperties(String key);
  4.stringPropertyNames();----->keySet方法

    public void test01(){
        Properties pro = new Properties();
        pro.setProperty("ruirui","211");
        pro.setProperty("haohao","985");
        pro.setProperty("guoguo","222");
        Set<String> s = pro.stringPropertyNames();
        for(String key:s){
            String value = pro.getProperty(key);
            System.out.println(key+" "+value);
        }
    }

二:把集合中的临时数据写到硬盘上  

  store 把流中临时的数据  持久化到硬盘中存储
  load把硬盘中的文件(键值对) 读取到 集合中使用


    public void test02() throws IOException {
        Properties pro = new Properties();
        pro.setProperty("ruirui","211");
        pro.setProperty("haohao","985");
        pro.setProperty("guoguo","222");
        //1 创建字节输出流 //字符输出流    构造方法中要绑定输出的目的地
        //第一种方法
//        FileWriter fw = new FileWriter("d:\\a.txt");
//        pro.store(fw,"save data");
//        fw.close();
        //第二种方法
        pro.store(new FileWriter("d:\\a.txt"),"");
    }

三:使用properties集合中的方法,load 把硬盘中的文件(键值对)读取到集合中使用


    public void test03() throws IOException {
        // 1 创建集合
        Properties po = new Properties();
        // 2 load方法读取数据  并保存到对应的集合中
        po.load(new FileReader("d:\\a.txt"));
        //3  遍历集合po
        Set<String> s = po.stringPropertyNames();
        for(String key:s){
            String value = po.getProperty(key);
            System.out.println(key+"="+value);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章