当前位置:网站首页>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边栏推荐
猜你喜欢
随机推荐
Face recognition sample code analysis (1) - program parameter analysis
聚集索引和非聚集索引
堆(heap)系列_0x0A:3种方法一次性解决堆溢出问题
时间序列分析
【力扣】128. 最长连续序列
如何不使用第三个变量来交换两个数的值
Matlab做分布拟合及绘制频率分布直方图
【力扣】207. 课程表
qemu虚拟机模拟固件环境搭建
Principal Component Analysis - Applications of MATLAB in Mathematical Modeling (2nd Edition)
Vim实用技巧_0.vim - introduction
Vim实用技巧_7.模式匹配和查找
输入不定长数组,输入一个字符串,既包含字符,又包含数字,输出数组,输入一个二维数组,字符和数字都可
全局服务器调度简介
软件安全内存区域详解
Unity Shader 透视效果/XRay
杭州富阳科目三考试
软件安全基本概念
Detailed Explanation of Software Secure Memory Area
配置 vscode 让它变得更好用









