java--properties集合的读取、存储

java.util.Properties; 继承HashTable
建立一个xxx.properties文件 里面写键值对键值对之间不要有空格

package cn.bufanli.iodemo;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/**
 * @author BuShuangLi
 * @date 2018/12/27
 * 集合对象 Properties ,继承Hashtable,实现Map接口
 * 能够和IO对象结合使用,实现数据的持久存储
 */
public class PropertiesDemo {
     public static void main(String[] args) throws IOException{
         // saveKV();
          //特有的方法输入流
         // uniqueMethodIn();
          //特有的方法输出流
          uniqueMethodOut();
     }
     /**
      * 使用Properties对象存储键值对
      * setProperty(String key, String value) 至关于Map中的put
      * 使用Properties对象经过键获取存储的值
      * getProperty(String key);
      */
     private static void saveKV() {
          Properties properties = new Properties();
          //使用Properties对象存储键值对
          properties.setProperty("a","1");
          properties.setProperty("b","2");
          properties.setProperty("c","3");
          System.out.println(properties);
          //使用Properties对象经过键获取存储的值
          String c = properties.getProperty("c");
          System.out.println(c);
          //方法将集合中的全部的键存储到set的集合当中
          Set<String> strings = properties.stringPropertyNames();
          for (String string : strings) {
               System.out.println(properties.getProperty(string));
          }
     }
     /**
      * Properties特有的方法
      */
     private static void uniqueMethodIn() throws IOException {
          //建立Properties集合对象
          Properties properties = new Properties();
          //建立文件输入流对象给出数据源
          FileReader fileReader = new FileReader("f:\\a.properties");
          //传递任意字符或者字节输入流 流对象读取文件的键值对存储到properties集合当中
          properties.load(fileReader);
          //关流
          fileReader.close();
          //遍历properties集合对象
          Set<String> strings = properties.stringPropertyNames();
          //遍历
          for (String string : strings) {
               System.out.println(properties.getProperty(string));
          }
     }

     /**
      * Properties特有的方法
      */
     private static void uniqueMethodOut() throws IOException{
          //建立Properties集合对象
          Properties properties = new Properties();
          //存入一些键值对
          properties.setProperty("name","李四");
          properties.setProperty("age","18");
          properties.setProperty("money","12222222");
          //建立文件输入流对象给出数据源
          FileWriter fileReader = new FileWriter("f:\\a.properties");
          properties.store(fileReader,"zhongwen");
          //关流
          fileReader.close();
     }
}