属性文件加载

一、文件加载

基于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");

 

posted @ 2022-04-14 17:25  Matt_Cheng  阅读(21)  评论(0编辑  收藏  举报