0

我有一个包含不同属性文件中属性的键:值数据的 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();
    }
}
4

1 回答 1

4

维护一组 Properties + 它们相应的文件名有什么问题?如果你将这些封装在一个对象中,那么你只需要循环,那个对象就会知道如何更新和写出自己。

于 2012-08-17T08:53:08.883 回答