Java Properties相关使用

133 阅读1分钟

介绍

    Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
特点:
1.Map接口的子类,map中的方法都可以用。
2.该集合没有泛型。键值都是字符串。
3.它是一个可以持久化的属性集。键值可以存储到集合中,也可以存储到持久化的设备(硬盘、U盘、光盘)上。键值的来源也可以是持久化的设备。
4.有和流技术相结合的方法。

使用

public static void main(String[] args) throws IOException {
   //properties 要求使用键值对
    Properties  p= new Properties();
    FileReader f = new FileReader("test.properties");
    //加载配置文件到集合中
    p.load(f);
    //通过键获取值
    String name = p.getProperty("name");
    //获取所有的数据,获取所有的键
    Set<String> list = p.stringPropertyNames();
    for (String s:list){
        String value = p.getProperty(s);
        System.out.println(s+"="+value);
    }
    f.close();
    //store追加或重写properties文件
    Properties p = new Properties();
    p.setProperty("name", "xiaowang");
    p.setProperty("age", "20");
    p.setProperty("sex", "nan");
    p.setProperty("address", "changzhou");
    Writer w = new FileWriter("test.properties",true);
    p.store(w, "添加属性");
    w.close();
}

包装

public class PropertiesUtils {
    private static Properties p = new Properties();
    //静态语句块 提前运行
    static{
        try {
            FileReader f = new FileReader("test.properties");
            p.load(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getValueByKey(String key){
        return p.getProperty(key);
    }
}