40.Properties

概述

 1.Properties作为Map使用

//      创建对象不可使用泛型
        Properties properties = new Properties();
//        存储元素
        properties.put("张飞","18");
        properties.put("关羽","19");
        properties.put("刘备","20");
        Set<Object> objects = properties.keySet();
//        遍历元素
        for (Object o:objects){
            System.out.println(o+":"+properties.get(o));
        }

 2.Properties作为Map使用的特有方法

//        setProperty​(String key, String value) 设置集合的键和值,都是String类型,调用 Hashtable方法 put 。
        Properties prop = new Properties();
        prop.setProperty("001","张飞");
/**
 *     public synchronized Object setProperty(String key, String value) {//注意学习这种设计方法
 *         return put(key, value);
 *     }
 *     public synchronized Object put(Object,Object){
 *          return map.put(Object,Object);
 *     }
 */
        prop.setProperty("002","关羽");
        prop.setProperty("003","刘备");
//        String getProperty​(String key) 使用此属性列表中指定的键搜索属性。
        System.out.println(prop.getProperty("001"));//张飞
//        Set<String> stringPropertyNames​() 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串

        Set<String> strings = prop.stringPropertyNames();
        for (String s:strings){
            System.out.println(s+":"+prop.getProperty(s));
        }

2.Properties和IO相结合

        myStore();
        myLoad();

//    把集合中的元素保存到文件
    private static void myStore() throws IOException {
        Properties prop = new Properties();
        prop.setProperty("001","张飞");
        prop.setProperty("002","关羽");
        prop.setProperty("003","刘备");
        FileWriter fileWriter = new FileWriter("file\prop.txt");
        prop.store(fileWriter,"這是注释信息!!!");//第二个参数是注释信息
        fileWriter.close();
    }
//    把文件中的数据加载到集合
    private static void myLoad() throws IOException {
        Properties prop = new Properties();
        FileReader fileReader = new FileReader("file\prop.txt");
        prop.load(fileReader);
        System.out.println(prop);
        fileReader.close();
    }
原文地址:https://www.cnblogs.com/luzhanshi/p/13192135.html