I have a Map that contains key:value data for properties that are in different properties files. I came to the following solution:
//firstProp - properties file
//FIRST_PROPERTIES_FILE - path to a properties file
public void changeProps(Map<String, String> props) {
boolean isFirstPropsChanged = false;
boolean isSecondPropsChanged = false;
boolean isThirdPropsChanged = false;
Set<String> keys = props.keySet();
for(String key : keys) {
if(firstProp.containsKey(key) && !firstProp.getProperty(key).equals(props.get(key))) {
firstProp.setProperty(key, props.get(key));
if(!isDirstPropsChanged) {
isFirstPropsChanged = true;
}
}
if(secondProp.containsKey(key) && !secondProp.getProperty(key).equals(props.get(key))) {
secondProp.setProperty(key, props.get(key));
if(!isSecondPropsChanged) {
isSecondPropsChanged = true;
}
}
if(thirdProp.containsKey(key) && !thirdProp.getProperty(key).equals(props.get(key))) {
thirdProp.setProperty(key, props.get(key));
if(!isThirdPropsChanged) {
isThirdPropsChanged = true;
}
}
}
try {
if(isFirstPropsChanged){
firstProp.store(new FileOutputStream(FIRST_PROPERTIES_FILE), null);
}
if(isSecondPropsChanged) {
secondProp.store(new FileOutputStream(SECOND_PROPERTIES_FILE), null);
}
if(isThirdPropsChanged) {
thirdProp.store(new FileOutputStream(THIRD_PROPERTIES_FILE), null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This solution works well, but it looks like wheelchair. I looked through different DPs, Strategy seemed to be good here, but it only seemed… I even think that no DP should be applied and that there’s much delicate and simpler solution. But what it is in fact?
Updated
Refactoring according to Brian Agnew suggestion or smth. alike.
//Map<Properties, File> propertiesFileMap - Properties files with File they are located at.
public void changePropsArray(Map<String, String> props) {
Set<String> keys = props.keySet();
for(String key : keys) {
for(Properties prop : propertiesFileMap.keySet()) {
if(prop.containsKey(key) && !prop.getProperty(key).equals(props.get(key))) {
prop.setProperty(key, props.get(key));
}
}
}
try {
for(Map.Entry<Properties, File> entry : propertiesFileMap.entrySet()) {
entry.getKey().store(new FileOutputStream(entry.getValue()), null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
What’s the matter with maintaining an array of Properties + their corresponding filename ? If you encapsulate these in an object then you simply have to loop through and that object will know how to update and write itself out.