修改或添加值时重置属性文件

时间:2015-04-20 13:29:09

标签: java xml properties-file

我需要的是一种简单的方法来读取和写入XML文件的某些值?我希望它像这样简单:

Configuration config = new Configuration();
config.setValue("WIDTH", 1000);
int WIDTH = config.getValue("WIDTH");

它必须始终可写和可读。这就是我到目前为止所做的:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class Configuration {
    Properties config;

    public Configuration() {
        config = new Properties();
    }

    public void setValue(String name, String value) {
        try {
            config.setProperty(name, value);
            config.storeToXML(new FileOutputStream("MyXmlConfig.xml"), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getValue(String name) {
        try {
            config.loadFromXML(new FileInputStream("MyXmlConfig.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return config.getProperty(name);
    }
}

我的问题是它在更新或添加变量时重置创建的文件。

1 个答案:

答案 0 :(得分:0)

内置类java.util.Properties支持此用例:

Properties config = new Properties();
config.loadFromXML(new FileInputStream("c:/MyXmlConfig.xml"));
config.setProperty("WIDTH", "1000");
int WIDTH = Integer.parseInt(config.getProperty("WIDTH"));
config.storeToXML(new FileOutputStream("c:/MyXmlConfig.xml"), "My config file");
相关问题