设置属性,并将它们存储在文件中

时间:2013-12-03 16:25:15

标签: java oop file-io

我有一个类,它从包中处理给定的“配置文件”。由于我只需要处理简单的键/值对,我认为使用Properties就行了。

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigFile {

    private Properties appProps = new Properties();
    private String filename;
    private InputStream in;

    public ConfigFile(String file) throws FileNotFoundException, IOException {
        this.filename = file;
        in = getClass().getResourceAsStream(this.filename);
        appProps.load(in);
        in.close();
    }

    public String getProp(String key) {
        return appProps.getProperty(key);
    }

}

现在,我想创建一个setProp(String key, String value)方法,显然 - 设置给定的属性,并将其保存到它读取的同一个文件中。我似乎无法弄清楚如何做到这一点。我想我需要打电话给appProps.setProperty(key, value),然后使用OutputStream做一些魔法,但我坚持认为。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

        Properties prop = new Properties();

    try (FileOutputStream os = new FileOutputStream("config.properties"))
    {
        //set the properties value
        prop.setProperty("database", "localhost");
        prop.setProperty("dbuser", "mkyong");
        prop.setProperty("dbpassword", "password");

        //save properties to project root folder
        prop.store(os, null);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

这应该解释一切,如果不随意问。

答案 1 :(得分:1)

自动保存的此功能不直接在Properties类中提供,但您可以撰写现有功能。您必须自己实现此组合,可以通过继承Properties并实现新方法或添加实用程序方法。如果您对现有属性不感兴趣,可以编写如下代码:

void update(String file, String key, String value) throws IOException {
    Properties properties = new Properties();
    InputStream is = new FileInputStream(new File(file));
    try {
    properties.load(is);
    } finally {
      is.close();
    }
    properties.setProperty(key, value);
    OutputStream os = new FileOutputStream(new File(file));
    try {
      properties.store(os);
    } finally {
      os.close();
    }
}