FileInputStream加载文件的倒数第二个版本

时间:2018-07-23 09:37:15

标签: java io

我有一个简单的方法,可以在修改文件后重新加载配置。

    private Properties loadCustomProperties(File config) throws IOException {
        Properties properties = new Properties();
        try (FileInputStream inStream = new FileInputStream(config)) {
            properties.load(inStream);
        }
        return properties;
    }

现在,如果我从IDE(Intellij)运行此代码,一切正常,但是当使用Spring bootstrap jar运行时,它将加载文件的第二个版本。因此,基本上,如果我的初始值prop = 1,然后将其更改为prop = 2,则仍然加载了prop = 1。如果将其更改为prop = 3,则最终会加载了prop = 2,依此类推。

系统为Ubuntu 18.04。

属性如下:

cache.size=1000

预期的输出是获取文件的最新版本。

1 个答案:

答案 0 :(得分:0)

我建议您构建一种实用程序方法来读取单个属性,以便可以轻松地按1逐个加载所需的所有属性,例如(在我的示例中,配置文件名为 config.properties ):

public static String getPropertyValue(String property) throws IOException {

    Properties prop = new Properties();
    String propFileName = "config.properties";
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream(propFileName);

    if (inputStream != null) {
        prop.load(inputStream);
    } else {
        throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
    }

    return prop.getProperty(property);
}

因此,如果在您的config.properties文件中输入

cache.size=1000

致电getPropertyValue("cache.size")会得到1000

相关问题