当前位置:网站首页>properties文件的读取和写入
properties文件的读取和写入
2022-08-09 15:01:00 【鸣筝鸣筝】
目录
properties文件是一种属性文件,这种文件以key=value(键值对)格式存储内容。Java中可以使用Properties类来读取这个文件,使用Properties类中的getProperties(key)方法来得到对应的数据。一般properties文件作为一些参数的存储,使得代码更加灵活。
一、properties文件的读取
(1)使用BufferedInputStream(缓冲输入流)创建输入流进行读取,读取后以key=value(键值对)格式存储数据。
代码实现:
//Properties格式文件的读取
//创建输入流
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\student\\aaa.properties"))) {
int data =-1;
while((data=bis.read())!=-1) {
System.out.print((char)data);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//运行结果
//k=12
//b=34
//c=11
(2)使用Properties类中的load()方法读取,将“输入流”加载到Properties集合对象中,根据key来获取value的值
代码实现:
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\student\\aaa.properties"))) {
Properties props=new Properties();
props.load(bis);//将“输入流”加载到Properties集合对象中
//根据key,获取value
System.out.println(props.get("k"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//运行结果
//12
二、properties文件的写入
因为properties文件数据是以集合形式存储,所以可以用put()方法将KV键值对存入Properties集合中,再通过输出流使用store()方法将集合中的临时数据,持久化写入硬盘中存储。
//properties格式文件的写入
try{
Properties props=new Properties();
props.put("Q", "123");
props.put("W", "432");
props.put("E", "986");
props.put("R", "457");
//使用“输出流”,将properties集合中的KV键值对,写入*.properties文件
try (BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("D:\\student\\bbb.properties"))) {
props.store(bos, "just do IT");
}
} catch (IOException e) {
e.printStackTrace();
}
//运行结果
// #just do IT
// #Wed Jun 01 00:14:57 CST 2022
// W=432
// R=457
// Q=123
// E=986
边栏推荐
猜你喜欢
随机推荐
Unity Shader零基础入门4:纹理贴图与法线贴图
模糊综合评价
idea 用不了Ctrl+Shift+F快捷键全局搜索。
hugging face tutorial - Chinese translation - share a model
Unity Shader零基础入门3:逐像素光照、Blinn-Phong、透明度
SVM支持向量机——MATLAB在数学建模中的应用
2022.7.16学习总结
【QT】窗口几何布局学习
GStreamer应用开发手册学习笔记之二
【翻译】制作DEB/debian包
Markdown 文档生成 PDF
事务的隔离级别
前置后置运算符重载
2022.7.18学习总结(Verilog HDL数字集成电路设计原理与应用)
MATLAB Solution to Planning Problems - MATLAB in Mathematical Modeling (2nd Edition)
Excel绘制统计图
数据拟合方法 MATLAB在数学建模中的应用(第二版)
Basic Concepts of Software Security
Data Fitting Methods Application of MATLAB in Mathematical Modeling (Second Edition)
DOS命令