Properties概述和使用

一、概述

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

public static void demo1() {
   Properties prop = new Properties();
   prop.put("abc", 123);
   System.out.println(prop);
}

二、特殊功能

 Object setProperty(String key, String value)
          调用 Hashtable 的方法 put
 String getProperty(String key)
          用指定的键在此属性列表中搜索属性。
Enumeration<?> propertyNames()
          返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键。
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);
   }
}

三、load()和store()

 void load(InputStream inStream)
          从输入流中读取属性列表(键和元素对)。
 void store(OutputStream out, String comments)
          以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

注:这两个方法常用于读取配置文件

public static void main(String[] args) throws FileNotFoundException, IOException {
   Properties prop = new Properties();
   prop.load(new FileInputStream("config.properties"));      //将文件上的键值对读取到集合中
   prop.setProperty("tel", "18912345678");
   //第二个参数是对列表参数的描述,可以给值,也可以给null
   prop.store(new FileOutputStream("config.properties"), null);
   System.out.println(prop);
}

猜你喜欢

转载自blog.csdn.net/qq_40298054/article/details/87175682