Java读取properties配置文件

假设我们要读取一个文件名为resource.properties的配置文件,其中只有如下内容:

test=hello

目前我知道的读取properties配置文件有如下两种方式:

1.使用java.util.Properties类读取,代码如下:

InputStream inputStream = new FileInputStream(new File("XXX"));
Properties properties = new Properties();
properties.load(inputStream);
String test = properties.getProperty("test");

2.使用java.util,ResourceBundle读取,对应代码为(假设resources.properties在类路径下):

ResourceBundle bundle = ResourceBundle.getBundle("resource"); // 此处不用包含后缀.properties
bundle.getString("test");

使用方法1时,当我们修改配置文件后执行代码,会读取出最新的内容;

而当我们使用方法2时,修改配置文件后,执行代码读取的值不会改变,因为ResourceBundle中会有缓存,当我们读取的时候会读取缓存中的内容。

目前如果要使用方法2,并且需要在修改配置文件后立即更新,可以使用 ResourceBundle.clearCache();方法来清楚缓存,重新读取最近的文件中的内容。

原文地址:https://www.cnblogs.com/zawier/p/6724090.html