Reputation: 1128
I have some requirement where I want to write/update the value in the properties file I am using the my spring application.
I have googled it but I have not found a direct way of doing it using Spring.
Does any one aware of how to do it or is there any best way to do it.
Thanks in advance.
Upvotes: 16
Views: 23120
Reputation: 499
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();
}
}
EDIT : updated with the defaultPropertiesPersiter from org.springframework.Util
Upvotes: 22
Reputation: 68962
Extending the existing answer by @deh, read and write using spring-boot. Note it is not using the typical classpath: in @PropertySource. To automate writing of more properties you could enumerate all fields with reflection.
@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();
}
}
}
Upvotes: 0