在Spring中写入/更新属性文件值


问题内容

我对使用Spring应用程序的属性文件中的值进行写入/更新时有一些要求。

我已经用谷歌搜索过,但是我没有找到使用Spring的直接方法。

是否有人知道该怎么做或是否有最佳方法。

提前致谢。


问题答案:

您可以这样实现:

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

资源

编辑:使用来自org.springframework.Util的defaultPropertiesPersiter更新