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

问题描述 投票:0回答:2

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

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

有人知道如何做吗?或者有没有最好的方法。

提前致谢。

java spring properties-file
2个回答
22
投票

你可以这样实现:

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 进行更新


0
投票

扩展 @deh 的现有答案,使用 spring-boot 进行读写。 请注意,它没有使用典型的类路径:@PropertySource。 要自动写入更多属性,您可以使用反射枚举所有字段。

@Data
@Configuration
@PropertySource("file:offset.properties")
public class Offset {

    @Value("${offset:0}")
    private int offset;

    public void save(int newOffset) {
        try {
            Properties props = new Properties();
            props.setProperty("offset", "" + newOffset);
            File f = new File("offset.properties");
            OutputStream out = new FileOutputStream( f );
            DefaultPropertiesPersister p = new DefaultPropertiesPersister();
            p.store(props, out, null);
        } catch (Exception e ) {
            e.printStackTrace();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.