当前位置:网站首页>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
边栏推荐
猜你喜欢
使用NATS及其nats.c客户端简单示例用法(nats.c的API接口)
堆(heap)系列_0x08:NT堆调试支持_立刻发现调试支持(DPH)
Vim practical skills_0.vim - introduction
全局服务器调度简介
Vim practical skills_4. Manage multiple files (open + split + save + netrw)
PE格式系列_0x05:输出表和重定位表(.reloc)
如何通过Photoshop根据纹理贴图轻松获得法线贴图
The practical skills Vim _5. Move quickly between files and documents
数学规划模型
转载-文件资源管理器无响应的解决办法
随机推荐
TCP/IP协议组——完整工作过程分析
如何不使用第三个变量来交换两个数的值
godot正确设置2d像素游戏
数据拟合方法 MATLAB在数学建模中的应用(第二版)
Gray Relevance Matrix——Application of MATLAB in Mathematical Modeling
【QT】窗口的显示与模态窗口
主成分分析——MATLAB在数学建模中的应用(第2版)
层次分析法
websocket协议详解
杭州富阳科目三新规3号线考试攻略
使用NATS及其nats.c客户端简单示例用法(nats.c的API接口)
【Postgraduate Work Weekly】(Week 5)
CTF online encryption and decryption and common tools
软件测试流程
Face recognition sample code analysis (1) - program parameter analysis
时间序列分析
【Likou】1995. Statistical special quadruple
Unity Shader零基础入门2:环境光、漫反射、高光
GStreamer应用开发手册学习笔记之二
Vim实用技巧_5.在文件间和文件内快速移动