写入由 ClassLoader 加载的 Wildfly 上的属性文件

Write to properties file on Wildfly which is loaded by ClassLoader

我正在像这样在 Wildfly 应用程序服务器上加载属性:

public String getPropertyValue(String propertyName) throws IOException {
    InputStream inputStream;
    Properties properties = new Properties();

    inputStream = getClass().getClassLoader().getResourceAsStream(propertyFileName);

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

    inputStream.close();
    String property = properties.getProperty(propertyName);
    LOG.debug("Property {} with value {} loaded.", propertyName, property);
    return property;
}

现在我想写入同一个文件。我该怎么做才正确?我尝试使用 new File(configurationFileName),但它在不同的目录中创建了一个新文件,我尝试使用来自类加载器的 URL/URI 文件,但这似乎也不起作用。这样做的正确方法是什么? 感谢您的帮助!

你不能也不应该。我会使用数据库 table 来存储和加载属性。或者,如果它应该是一个属性文件,则通过文件路径将其存储在外部某处,而不是通过 class 路径。

try (FileOutputStream out = new FileOutputStream(new File( getClass().getClassLoader().getResource(propertyName).toURI()))){
    properties.store(out,"My Comments);
}

Raoul Duke 其实是对的,通过文件做属性会带来很多问题。我将很快切换到 DB 来保留这些。同时我这样做了:当我写属性时,它们被写入一个新创建的文件。当我读取属性时,我加载 "old" 个,然后创建一个新的属性对象,将旧的作为默认值,然后在其中加载新文件。

private Properties loadProperties() throws IOException {
    InputStream inputStream;
    Properties defaultProperties = new Properties();
    inputStream = getClass().getClassLoader().getResourceAsStream(defaultPropertyFileName);
    if (inputStream != null) {
        defaultProperties.load(inputStream);
    } else {
        throw new FileNotFoundException("Property file '" + defaultPropertyFileName + "' not found in the classpath");
    }
    inputStream.close();
    Properties allProps = new Properties(defaultProperties);
    try {
        allProps.load(new FileInputStream(new File(updatedPropertyFileName)));
    } catch (IOException ex) {
        LOG.error("Error loading properties: {}", ex.toString());
        return defaultProperties;
    }
    return allProps;
}

我将他的答案标记为正确,因为从技术上讲我没有写入我想要的文件,而且这只是一种解决方法,他的解决方案更好更清晰。