当前位置:网站首页>Properties文件的读取与保存
Properties文件的读取与保存
2022-08-08 06:28:00 【记得爱蓝色】
一、Properties格式的读取
Properties是一种格式文件,在java中Properties类继承自Hashtable,是一种键值对(Key== Value)形式进行存储内容,实质上也是一种集合。
进行 Properties文件的读取,使用BufferedInputStream创建输入流,创建Properties类的对象,调用load()方法 ,将“输入流”加载至Properties集合对象中。
源码如下:
package com.yx.demo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo03 {
public static void main(String[] args) {
//Properties格式文件的读取
//创建输入流
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:\\test\\aaa\\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) {
e.printStackTrace();
}
Properties也提供store()方法,将值写入*.properties文件。
二、Properties格式文件读取
我们在读取文件时,为了避免不同环境下的文件路径不一致的问题,通过class path读取当前相对路径下的文件,class path : 当前项目编译后的bin目录,我们将*.properties文件保存在class path 根目录,然后获取当前的class对象,然后调用getResourceAsStream()方法可以直接从classpath读取任何路径下的文件。然后通过properties的load()方法加载读取。
实现代码如下:
package com.yx.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Demo04 {
public static void main(String[] args) {
try (InputStream in = Demo04.class.getResourceAsStream("/com/yx/demo/temp.properties")) {
//加载读取
Properties props = new Properties();
props.load(in);
System.out.println(props);
} catch (IOException e) {
e.printStackTrace();
}
}
}
边栏推荐
猜你喜欢
随机推荐
【图形学】05 渲染管线基础
模块及模块导入
Mysql大并发热点行更新的两个骚操作
tcpdump进行DNS抓包
Solved the problem that when VRTK transmission under Unity HDRP, the screen fades in and out, and the visual occlusion cannot be displayed correctly when passing through the wall
【图形学】03 数学部分(三、各种变换矩阵)
Unity_雷达图(属性图)+ UI动画
webAPI
C# Unicode (Universal Code) text conversion
一文带你了解webrtc基本原理(动手实现1v1视频通话)
Day38------网络相关
Unity_圆环滑动条(圆形、弧形滑动条)
Unity学习笔记 01 —— 常用API
【图形学】 06 四元数(一)
编程更改镜像总结
括号问题
Stack queue OJ question sharing and explanation
minikube metrics-server HPA 自动扩缩容错误
minikube addons enable ingress 启动错误
模块知识点补充









