当前位置:网站首页>properties文件的读取和写入
properties文件的读取和写入
2022-07-18 18:01:00 【爱喝冰红茶阿】
什么是properties文件?
properties文件是一种属性文件,这种文件以key=value格式存储内容。Java中可以使用Properties类来读取这个文件,使用Propertie类中的getProperty(key)方法就能得到对应的数据。一般properties文件作为一些参数的存储,使得代码更加灵活。
Properties文件的读取:
普通读取:利用BufferInputStream缓冲输入流进行读取,可以读取到文件的所有内容,但这样读取失去了properties文件的特点。这种文件是以key=value格式存储内容。
代码实现:
public class Main {
public static void main(String[] args) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:\\IO流\\data.properties"))) {
int data = -1;
while((data = bis.read())!=-1) {
System.out.print((char)data);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用Properties类读取:我们需要使用load()方法将“输入流”加载至Properties集合对象中。这样我们就可以根据key来获取value的值。
代码实现:
public class Main {
public static void main(String[] args) {
try ( BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\IO流\\data.properties"))) {
Properties props = new Properties();
props.load(bis); //将“输入流”加载至Properties集合对象中
//根据key,获取value
System.out.println(props.get("cn"));
System.out.println(props.get("kr"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Properties文件的写入:
首先需要创建一个Properties对象props,使用put()方法将键和值放入Properties集合对象中,然后需要借助输出流通过store()方法把集合中的临时数据,持久化写入到硬盘中存储。
代码实现:
public class Main {
public static void main(String[] args) {
//Properties格式文件的写入
Properties props = new Properties();
props.put("f1", "2222");
props.put("f2", "2342");
//使用输出流,将Properties集合中的KV键值对,写入.properties文件
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\IO流\\demo.properties"))) {
props.store(bos, "just do it");
} catch (IOException e) {
e.printStackTrace();
}
}
}
边栏推荐
猜你喜欢
usage: convert.py [-h] [-p] [-w] config_path weights_path output_pathconvert.py: error: the followi
Nestjs first experience
前缀中缀后缀表达式(书面转换)
WPS如何一页一页设置页眉
pycharm代码规范工具flake8
提高出图效率,还可以这样玩?一招教你再也不用重复出图了
HOOPS 2022产品更新峰会5月来袭 ,3D核心技术再提升,不见不散
Overview of Routing Protocol BGP - must see for entry
jsp隐式对象-Servlet对象
三维高清vR展示模型的应用及优势
随机推荐
Copy structure to string
Explain some difficult knowledge about the switch
2022-7-9 个人排位赛6 比赛心得
Printf format output symbol detailed description
WPS如何一页一页设置页眉
C language reads txt files and sorts the output
vr虚拟现实展示是怎么实现的
YOLOV3
收藏!Solidworks设备布局工具:SOLIDWORKS Asset Publisher
SolidWorks直播课 | 3D参数化建模的实现方式
GPU memory limit when tensorflow2/1 and keras are used (occupancy ratio / specify maximum limit memory, etc.)
Inline function and macro definitions
剑指offer——队列
2022-7-8 个人排位赛5 比赛心得(补)
2022-07-12 第五小组 顾祥全 学习笔记 day05
黑龙江数字孪生智慧园区建设,全面整合园区内外部资源
3dvr虚拟现实展会开创展会展厅的线上模式
2022 HOOPS产品简介 | HOOPS Exchange、HOOPS Visualize、HOOPS Communicator、HOOPS Publish
基于模型的定义助力企业降本增效提高质量 | Solidworks白皮书
B题目:RAZLIKA 优先队列做法