【问题标题】:How to update a property file?如何更新属性文件?
【发布时间】:2011-11-04 09:21:49
【问题描述】:

我正在使用 classLoader 方法来加载属性文件。使用它,我可以检索属性的值,但现在我想更新某些属性的值,但我无法做到。请帮忙。这是代码:

InputStream inputStream = this.getClass().getClassLoader() .getResourceAsStream("PublishDate.properties");

try {
    Properties properties = new Properties();

    try {
       // load the inputStream using the Properties
       properties.load(inputStream);
    }
    catch(Exception e) {
       e.printStackTrace();
    }
    // get the value of the property
    String propValue = properties.getProperty("lastHtlProcessPublishDate");

在这里,在 propValue 中,我从文件中获取正确的值。我是这样更新的:

properties.put("lastHtlProcessPublishDate",dateFormatter.format(new Date()));   
properties.store(new FileOutputStream("PublishDate.properties"), null);

使用这个值不会得到更新,但是当我提供PublishDate.properties 的完整路径时,它就可以工作了。 但是,我不想给出完整的路径,因为路径是动态的。有人知道如何使用一些相对路径来做到这一点。请给我建议。

【问题讨论】:

    标签: java properties


    【解决方案1】:

    使用Apache's Commons Configuration API 处理您的属性文件。它将使读取和写入属性文件(任何配置文件)......让您的生活更轻松。

    编辑

    • 下载公共配置二进制文件here
    • 把它放在你的类路径中(lib 目录,如果你的项目有的话)
    • 运行干净并构建您的项目,以便 Eclipse(我假设)可以选择新类
    • 为您的操作和代码导入所需的类。 :D

    【讨论】:

    • 嗨,我更新了我的代码:PropertiesConfiguration config = new PropertiesConfiguration("PublishDate.properties"); config.setProperty("lastHtlProcessPublishDate",dateFormatter.format(new Date()) ); config.save();但我在控制台上得到了这个:线程“Thread-1”中的异常 java.lang.NoClassDefFoundError: org/apache/commons/configuration/PropertiesConfiguration at com.galileo.localdata.servlets.MVSDataServlet.run(MVSDataServlet.java:176)在 java.lang.Thread.run(Thread.java:619) 引起:java.lang.ClassNotFoundException: org.apache.commons.configuration.PropertiesConfiguration
    • 您是否导入了 PropertiesConfiguration 类?这就是那个错误的意思。
    • 是的,我导入了这个类,并且还放置了相同的罐子
    • 然后运行你的项目的cleanbuild,这样Eclipse(我假设)就可以选择新的类
    • 完成但仍然出现相同的错误。我之前得到的类型 org.apache.commons.lang.exception.NestableException 无法解决。它是从所需的 .class 文件中间接引用的。所以,为了解决这个问题,我添加了 commons-lang-exception-2.0.jar 来构建路径。是不是因为这个而出现这个错误?
    【解决方案2】:

    您可能想尝试commons-configuration 并使用PropertiesConfiguration。这应该可以满足您的所有需求。

    【讨论】:

    • final AbstractFileConfiguration fileConfiguration = new PropertiesConfiguration("PublishDate.properties"); fileConfiguration.setProperty("lastHtlProcessPublishDate", dateFormatter.format (new Date()));文件配置.save();
    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2016-08-26
    相关资源
    最近更新 更多