首先,我们得了解什么是Properties文件。Properties是一种配置文件,它继承自Hashtable并且实现了Map接口,所以Properties类的内部是以k-v键值对的方式存储数据的,而且实现了Map接口,因此,存储的数据是无序的。
Properties格式文件的读取:
要读取Properties文件,首先要创建输入流,
其次创建Properties类的对象,再调用Properties类的load()方法,将Properties属性文件对应的文件输入流,加载至Properties集合对象中。
最后根据key键,打印出对应的值。
public class test03 {
public static void main(String[] args) {
//Properties格式文件的读取
//创建输入流
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\KSWJJ\\aaa\\bbb\\ccc\\data.properties.txt"))) {
Properties props = new Properties();
props.load(bis); //将“输入流”加载至Properties集合对象中
//根据key,获取value
System.out.println(props.get("cd"));
} catch (IOException e) {
e.printStackTrace();
}
Properties格式文件的写入:
1.创建Properties集合对象
2.使用"输出流",再调用Properties类的store()方法将Properties集合中的kv键值对写入Properties文件。
//Properties格式文件的写入
try {
Properties prop = new Properties();
prop.put("f1", "1234");
prop.put("f2", "4567");
prop.put("f3", "1454");
prop.put("f4", "7894");
//使用"输出流",将Properties集合中的kv键值对写入Properties文件
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\\\KSWJJ\\\\aaa\\\\bbb\\\\ccc\\\\demo.properties"))) {
prop.store(bos,"just do IT");
}
}catch (Exception e1) {
e1.printStackTrace();
}