2015-07-10 45 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