我有一个Map,其中包含不同属性文件中属性的键:值数据。我找到了以下解决方案:
//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();
}
}
此解决方案效果很好,但看起来像轮椅。我查看了不同的DP,策略似乎在这里很好,但它似乎只是......我甚至认为不应该应用DP,并且有更多精致和简单的解决方案。但它究竟是什么呢?
更新 根据Brian Agnew的建议或smth进行重构。一样的。
//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();
}
}
答案 0 :(得分:4)
维护属性数组+相应的文件名有什么问题?如果将它们封装在一个对象中,那么你只需要遍历,该对象将知道如何更新和自行编写。