2015-07-10 46 views
9

我有一些要求在我要使用我的彈簧應用程序的屬性文件中編寫/更新值。在春天寫入/更新屬性文件的值

我已經使用了它,但我還沒有找到使用Spring的直接方法。

有沒有人知道如何去做,或者有沒有最好的辦法來做到這一點。

在此先感謝。

回答

12

你可以做到這一點是這樣的:

public void saveParamChanges() { 
    try { 
    // create and set properties into properties object 
    Properties props = new Properties(); 
    props.setProperty("Prop1", "toto"); 
    props.setProperty("Prop2", "test"); 
    props.setProperty("Prop3", "tata"); 
    // get or create the file 
    File f = new File("app-properties.properties"); 
    OutputStream out = new FileOutputStream(f); 
    // write into it 
    DefaultPropertiesPersister p = new DefaultPropertiesPersister(); 
    p.store(props, out, "Header COmment"); 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 
} 

source

編輯:從org.springframework.Util與defaultPropertiesPersiter更新

+3

感謝您的回答。但這是我知道的。我只想在春季通過一些方法來完成。 –

+0

@Yogesh就是你說的彈簧方法的意思嗎? – Deh

+2

@Yogesh,[DefaultPropertiesPersister]的Javadoc(http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/DefaultPropertiesPersister.html)的內容是:「從JDK 1.6開始,屬性.load/store也將被讀寫器使用,有效地將這個類轉換爲一個簡單的向後兼容適配器「,所以即使Spring沒有使用純Spring方法......它也使用了JDK方法。你應該接受德的答案。 – Paul