繁体   English   中英

写入由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;
}

现在,我要写入该文件。 我该怎么做呢? 我尝试使用新的File(configurationFileName),但是在另一个目录中创建了一个新的File,然后尝试使用类加载器中文件的URL / URI,但这似乎也不起作用。 正确的方法是什么? 谢谢!

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

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

Raoul Duke实际上是正确的,通过文件执行属性会带来很多问题。 我将很快改用DB来保留这些内容。 同时,我这样做:在编写属性时,它们将被写入新创建的文件中。 读取属性时,将加载“旧”属性,然后使用旧属性作为默认属性创建一个新的属性对象,然后在其中加载新文件。

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;
}

我标记了他的答案是正确的,因为从技术上讲我不是在写我想要的文件,而且这只是一种解决方法,并且他的解决方案更好,更干净。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM