【问题标题】:Properties file reset when modifying or adding value修改或添加值时重置属性文件
【发布时间】:2015-04-20 13:29:09
【问题描述】:

我需要一种简单的方法来读取和写入某些值到 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);
    }
}

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

【问题讨论】:

  • INI 文件更适合。
  • 嗯,对于简单的配置来说,这是一种很好的文件格式。 XML 也可以。
  • 我会使用 JSON 来实现。
  • INI 也可以工作,但我选择了 XML。除了看起来格式很好之外,没有其他原因。
  • @demostene,格式并不重要,只要它有效。

标签: java xml properties-file


【解决方案1】:

内置类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");

【讨论】:

  • 谢谢!我试试看。
  • 有效!有点.....我需要能够更新变量值。这(意味着我设置它的方式)重置文件。
猜你喜欢
  • 2014-04-14
  • 2015-12-21
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多