簡體   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