Properties属性集合

Properties属性类

Properties属性集合概述
    * 是一个双列集合,实现了Map接口,继承Hashtable类。
    
Properties集合的特点
    * 创建对象时不需要指定泛型
    * 键和值都是字符串
    * 可以和流技术相加使用
        * 可以直接通过流将集合中的数据保存到文件中
        * 可以直接从文件中读取数据到集合

属性文件要求
    * 命名要求:xxxx.properties
    * 存储格式:每个键值对占据一行,格式:键=
    * 文件中可以使用注释,注释是以 # 开头

Properties类常用方法
    * Object setProperty(String key, String value) 
        * 存储键值对 如果键存在,则使用新值替换旧值,返回旧值,否则返回null
    * String getProperty(String key)
        * 根据键获得值 
    * int size(); 获得键值对个数 
    * Object remove(Object key) 根据键删除键值对,返回键对应的值
    * Set<String> stringPropertyNames() 获得集合中的所有键
    
    * void store(Writer writer, String comments)
    * void store(OutputStream out, String comments)
        * 将集合中的数据保存到流关联的目标文件中
        * comments:描述信息字符串,一般给null即可
    
    * void load(InputStream in)
    * void load(Reader reader)
        * 从流关联的目标文件中读取数据到集合中

示例代码

public class PropertiesDemo {
    public static void main(String[] args) throws Exception{
        // 创建属性集合:双列集合
        Properties pros = new Properties();
        System.out.println(pros);
        // 创建字节输入流对象
        FileInputStream fis = new FileInputStream("bbb.properties");
        // 从文件中读取数据到集合中
        pros.load(fis);
        // 关闭流
        fis.close();
        System.out.println(pros);
    }
    
    /**
     * Properties集合:保存数据到文件中
     */
    public static void test02() throws Exception{
        // 创建属性集合:双列集合
        Properties pros = new Properties();
        pros.setProperty("name", "张三");
        pros.setProperty("age", "23");
        pros.setProperty("gender", "男");
        
        // 将集合中的数据保存到文件中:aaa.properties
        // 创建字节输出流
        FileOutputStream fos = new FileOutputStream("aaa.properties");
        pros.store(fos, null);
        // 关闭流
        fos.close();
    }
    
    /**
     * Properties集合常用方法演示
     */
    public static void test01() {
        // 创建属性集合:双列集合
        Properties pros = new Properties();
        // 存储元素
        Object name = pros.setProperty("name", "rose");
        System.out.println(name); // null
        name = pros.setProperty("name", "jack");
        pros.setProperty("gender", "男");
        System.out.println(name); // rose
        
        // 获取元素
        name = pros.getProperty("name");
        System.out.println(name); // jack
        System.out.println(pros.size()); // 2
        
        // 删除键值对
        // System.out.println(pros.remove("gender"));
        // System.out.println(pros.size()); // 1
        System.out.println("-----------------");
        // 获得键集合
        Set<String> names = pros.stringPropertyNames();
        for (String n : names) {
            System.out.println(n +"=" + pros.getProperty(n));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/h294590501/article/details/80218598