本次博客带领大家了解IO流中的Properties类,介绍它的常用方法和注意事项等等。
Properties类
- 专门用于读写配置文件的集合类,配置文件的格式:键 = 值。
- 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String。
- Properties的常用方法:
- load :加载配置文件的键值对到Properties对象。
- list :将数据显示到指定设备。
- getProperty(key) :根据键获取值。
- setProperty(key,value) :设置键值对到Properties对象。
- store :将Properties中的键值对存储到配置文件,在idea 中,保存信息到配置文件,如果含有中文,会存储为unicode码。
- 案例1:使用Properties类来读取mysql.properties 文件。
public class Properties02 {
public static void main(String[] args) throws IOException {
//使用Properties类来读取mysql.properties 文件。
//1. 创建Properties 对象
Properties properties = new Properties();
//2. 加载指定配置文件
properties.load(new FileReader("src\\com\\mysql.properties"));
//3. 把K-V显示到控制台
properties.list(System.out);
//4. 根据key 获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名="+user);
System.out.println("密码="+pwd);
}
}
- 案例2:使用Properties 类来创建 配置文件,修改配置文件内容。
public class Properties03 {
public static void main(String[] args) throws IOException {
//使用Properties 类来创建 配置文件,修改配置文件内容。
Properties properties =new Properties();
//创建
//1. 如果该文件没有key,就是创建
//2. 如果该文件有key,就是修改
properties.setProperty("charset","utf8");
properties.setProperty("user","汤姆");
properties.setProperty("pwd","888");
//将k-v 存储文件中即可
properties.store(new FileOutputStream("src\\com\\mysql2.properties"),null);
System.out.println("保存成功!");
}
}