目标:Properties属性集对象
Properties的概述和使用。(保存数据到属性文件)
Properties:属性集对象。
其实就是一个Map集合。也就是一个键值对集合。但是我们一般不会当集合使用,因为有HashMap。
Properties核心作用:
Properties代表的是一个属性文件,可以把键值对的数据存入到一个属性文件中去。
属性文件:后缀是.properties结尾的文件,里面的内容都是 key=value。
大家在后期学的很多大型框架技术中,属性文件都是很重要的系统配置文件。
需求:生成一个属性文件,里面存入用户名和密码信息。
Properties的方法:
– public Object setProperty(String key, String value) : 保存一对属性。
– public String getProperty(String key) :使用此属性列表中指定的键搜索属性值
– public Set stringPropertyNames() :所有键的名称的集合
– public void store(OutputStream out, String comments):保存数据到属性文件中去
– public void store(Writer fw, String comments):保存数据到属性文件中去
public class PropertiesDemo01 {
public static void main(String[] args) throws Exception {
// 1.创建一个属性集对象
Properties pro = new Properties();
// 2.存入用户名和密码
pro.setProperty("user","dlei");
pro.setProperty("password","003197");
System.out.println(pro);
// 3.把属性对象pro中的键值对数据存储到一个属性文件中去:生成配置文件。
/**
* 参数一:被保存的字节输出流管道
* 参数二:保存心得
*/
pro.store(new FileOutputStream("src/users.properties"),"我在国庆前快乐的保存了一个密码,I am very happy!!");
System.out.println("保存完成!");
}
}
Properties读取属性文件中的键值对信息。(读取)
public class PropertiesDemo02 {
public static void main(String[] args) throws Exception {
// 1.创建一个属性集对象
Properties pro = new Properties();
// 2.加载属性文件中的键值对数据到属性集对象pro中去。
pro.load(new FileInputStream("src/users.properties"));
// 3.输出
System.out.println(pro);
System.out.println(pro.getProperty("user"));
System.out.println(pro.getProperty("password"));
}
}