惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
F
Fortinet All Blogs
爱范儿
爱范儿
博客园 - Franky
MyScale Blog
MyScale Blog
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
B
Blog
P
Proofpoint News Feed
IT之家
IT之家
宝玉的分享
宝玉的分享
D
DataBreaches.Net
S
SegmentFault 最新的问题
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
M
MIT News - Artificial intelligence
L
LangChain Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
雷峰网
雷峰网
Stack Overflow Blog
Stack Overflow Blog
量子位
V
V2EX
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

博客园 - Matt_Cheng

AI编码实践 对于动态注册的bean,aop会生效吗? LLM VSCode快捷命令 图平台技术点 常用CMD命令 jupyter安装与使用 数据结构文章收藏 使用beeline访问hive Java线程异常处理 node.js待实践项目 spring boot问题记录 docker命令 IDEA环境配置与快捷命令 Spring MVC 使用介绍(十六)数据验证 (三)分组、自定义、跨参数、其他 Spring MVC 使用介绍(十五)数据验证 (二)依赖注入与方法级别验证 Spring MVC 使用介绍(十四)文件上传下载 2018年年终总结
属性文件加载
Matt_Cheng · 2022-04-14 · via 博客园 - Matt_Cheng

一、文件加载

基于ClassLoader,有两种方式

// resource/default.properties
// 方式一
InputStream in = UserService.class.getResourceAsStream("/default.properties");
// 方式二
InputStream in = UserService.class.getClassLoader().getResourceAsStream("default.properties");

两者路径差异:可参见 class.getResourceAsStream 注释。

文件加载顺序:ClassLoader先从当前类目录搜索文件,再从依赖jar包搜索。若加载多个文件或目录,可使用ClassLoader.getResources()

二、文件读取

对应jar包内的文件,通过classloader获取到文件流后,若基于InputStream.available()先获取文件长度,再通过InputStream.read()一次性读取,文件可能读取不全。正确的实现如下:

InputStream is = TestMain.class.getResourceAsStream("/en/en.json");

int tmp;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((tmp = is.read()) != -1) {
    bout.write(tmp);   
}

String json = new String(bout.toByteArray(), StandardCharsets.UTF_8);

三、属性文件加载

1 基于Properties.load()

// resource/default.properties
InputStream in = UserService.class.getResourceAsStream("/default.properties");
Properties prop = Properties.load(in);

2 基于ResourceBundle.getBundle()

// resource/default.properties
ResourceBundle bundle = ResourceBundle.getBundle("default");
String value = bundle.getString("name");