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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31334977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:27:25  来源:igfitidea点击:

Write/Update properties file value in spring

javaspringproperties-file

提问by mevada.yogesh

I have some requirement where I want to write/update the value in the properties file I am using the my spring application.

我有一些要求,我想在我使用 spring 应用程序的属性文件中写入/更新值。

I have googled it but I have not found a direct way of doing it using Spring.

我在谷歌上搜索过它,但我还没有找到使用 Spring 的直接方法。

Does any one aware of how to do it or is there any best way to do it.

有没有人知道如何做到这一点,或者有什么最好的方法来做到这一点。

Thanks in advance.

提前致谢。

回答by Deh

You can achieve that like this :

你可以这样实现:

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

来源

EDIT : updated with the defaultPropertiesPersiter from org.springframework.Util

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