2015-10-23 24 views
0

加載我加載一個像這樣的Wildfly應用程序服務器上的屬性:寫入性能上Wildfly文件,該文件是由ClassLoader的

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,並且我嘗試了使用classloader的文件的URL/URI,但這似乎也不起作用。什麼是正確的方法來做到這一點? Thx求助!

回答

1

你不能,你不應該。我會使用數據庫表來存儲和加載屬性。或者如果它應該是一個屬性文件,然後通過文件路徑將其存儲在外部的某處,而不是通過類路徑。

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

請添加一些解釋。賦予基礎邏輯比賦予代碼更重要,因爲它可以幫助OP和其他讀者自己解決這個問題和類似的問題。 –

+0

在文件上獲取OutputStream,使用java.util.Properties中的store方法保存更改。這就是全部 – ehsavoie

+0

感謝您的答案。我得到的異常「java.lang.IllegalArgumentException:URI方案不是」文件「」 – olkoza

0

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

我標誌着他的答案正確的,因爲我技術上沒有寫,我想這個文件,再加上這只是一種變通方法和他的解決方案是更好的方式和更清潔。