23Properties(配置文件)

可持久化的映射类  继承Hashtable  键和值都应该是字符串

可持久化的意思就是可以存储在项目中,落实到本地的文件

生成的配置文件的后缀一定是.properties,默认编码是西欧编码

 中文转不了,按u16进行编码 配置文件可以随意改动

 

写入配置文件

public class PropertiesDemo {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        //创建对象
        Properties p=new Properties();
        //添加元素--键和值都是字符串
        p.setProperty("name","徐旺骑");
        p.setProperty("gender","女");
        p.setProperty("age", "10");
        //把要存储的内容传输到配置文件中  ---配置文件的后缀必须是.properties
        //第二个参数---文件的内容解释,就是告诉当前存入配置文件的内容做什么用的
        p.store(new FileOutputStream("p.properties"),"徐旺骑的基本信息");
        

    }

}

读取配置文件

public class PropertiesDemo2 {
public static void main(String[] args) throws FileNotFoundException, IOException {
    //创建对象
    Properties p=new Properties();
    //加载指定配置文件
    p.load(new FileInputStream("p.properties"));
    //获取配置文件的内容
    //根据键获取值
    System.out.println(p.getProperty("name"));//徐旺骑
    //根据键获取值
    System.out.println(p.getProperty("name", "丽丽"));//徐旺骑
    //列出配置文件信息
    p.list(System.out);
    /*
     * -- listing properties --
        age=10
        name=徐旺骑
        gender=女
        */
}
}

 

posted @ 2019-07-25 16:31  三十六烦恼风x  阅读(176)  评论(0编辑  收藏  举报