设置Java属性而不覆盖用户编写的值

时间:2015-02-10 16:48:36

标签: java

如果本地驱动器中不存在配置文件,我有一个使用Java Properties设置一些属性的方法。然而,我发现的坏事是即使我在我的代码中更改了一些属性,该方法只是检查文件是否存在并且不使用新属性更新文件。

另一个条件是用户可能覆盖了配置文件中的一个属性。因此,设置属性的方法不应该使用我的代码覆盖配置文件中的值。

这就是我做的事情

    private void setDefaultConfig() {
    try {
        if (!checkIfFileExists(configFile)) {
            setProperty(configFile, "cfgFile", "cfg.xml");
            setProperty(configFile, "type", "emp");
            setProperty(configFile, "url", "www.google.com");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

setPropertyMethod只是在指定文件上设置属性。

现在,如果我在方法中添加另一个属性,则用户无法获取新属性,因为我只是检查文件是否存在。

对于例如:如果用户更改了" url"财产有" www.yahoo.com"然后我在setDefaultConfig方法中的代码不应该用" www.google.com"

替换该值

有没有办法可以处理这种情况?

    protected void setProperty(String fileName, String property, String value) {
    Properties prop = new Properties();
    FileOutputStream fileOut = null;
    FileInputStream fileIn = null;
    try {
        File file = new File(fileName);
        if(checkIfFileExists(fileName)) {
            fileIn = new FileInputStream(file);
            prop.load(fileIn);
        }
        prop.setProperty(property, value);
        fileOut = new FileOutputStream(fileName);
        prop.store(fileOut, null);
    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

0 个答案:

没有答案