目录
1.掌握使用properties类读取属性文件中的键值对信息
2.掌握使用properties类向属性文件中输入键值对信息
3.判断是否存在彬,存在,将年龄改为18 (通过判断是否存在彬这个键 来判断)
Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式
1.掌握使用properties类读取属性文件中的键值对信息
1.load 方法读取属性文件
public class PropertiesTest1 {
public static void main(String[] args) throws Exception {
// 1.创建一个Properties对象出来(键值对集合,空容器)
Properties properties=new Properties();
System.out.println(properties);//{}
// 开始加载属性文件中的键值对数据到properties对象中去
properties.load(new FileReader("properties-xml-log-app\\src\\User.properties"));
System.out.println(properties);
// 3.根据建取值
System.out.println(properties.getProperty("张无忌"));
}
}
2.掌握使用properties类向属性文件中输入键值对信息
1.setProperty方法 存储键值对数据
2.store方法 把properties对象值的键值对数据存入到属性文件中去
import java.io.FileWriter;
import java.util.Properties;
public class PropertiesTest2 {
public static void main(String[] args) throws Exception {
// 1.创建Properties对象出来,先用它存储一些键值对数据
Properties properties=new Properties();
properties.setProperty("张无忌","22");
properties.setProperty("张无","122");
properties.setProperty("张","221");
// 2.把properties对象值的键值对数据存入到属性文件中去
properties.store(new FileWriter("properties-xml-log-app\\src\\User.properties" ),"Hello World");
}
}
3.案例
读取属性文件,判断是否存在 彬,存在年龄改成18
1.创建一个properties对象来接受数据
2.读取属性文件
3.判断是否存在彬,存在,将年龄改为18 (通过判断是否存在彬这个键 来判断)
4.把输出回properties文件
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Properties;
public class PropertiesTest3 {
public static void main(String[] args) throws Exception {
// 目标:读取属性文件,判断是否存在 彬 ,存在年龄改成18
/* 1.创建一个Properties对象来接收数据
2. 读取属性文件
3.判断是否存在彬,存在,将年龄改为18
4.把输出回文件
*/
// 1.创建一个Properties对象来接收数据
Properties properties=new Properties();
// 2.读取属性文件
properties.load(new FileReader("User.txt"));
System.out.println(properties);
// 3.判断是否存在彬,存在,将年龄改为18
// 通过判断是否存在键 来判断
if ( properties.containsKey("彬")){
properties.setProperty("彬","18");
}
// 4.输出到文件中去
// new FileWriter 创建一个字符输出流管道
properties.store(new FileWriter("User.txt"),"Hello World");
}
}