【问题标题】:Write/Update properties file value in spring在春季写入/更新属性文件值
【发布时间】:2015-09-28 20:39:51
【问题描述】:

我有一些要求,我想在我正在使用我的 spring 应用程序的属性文件中写入/更新值。

我已经用谷歌搜索了它,但我没有找到使用 Spring 的直接方法。

有没有人知道怎么做,或者有没有最好的方法。

提前致谢。

【问题讨论】:

    标签: java spring properties-file


    【解决方案1】:

    你可以这样实现:

    public void saveParamChanges() {
       try {
         // create and set properties into properties object
         Properties props = new Properties();
         props.setProperty("Prop1", "toto");
         props.setProperty("Prop2", "test");
         props.setProperty("Prop3", "tata");
         // get or create the file
         File f = new File("app-properties.properties");
         OutputStream out = new FileOutputStream( f );
         // write into it
         DefaultPropertiesPersister p = new DefaultPropertiesPersister();
         p.store(props, out, "Header COmment");
       } catch (Exception e ) {
        e.printStackTrace();
       }
    }
    

    source

    编辑:使用 org.springframework.Util 中的 defaultPropertiesPersiter 更新

    【讨论】:

    • 感谢您的回答。但这是我知道的。我只想在春天通过一些方法来做到这一点。
    • @Yogesh,DefaultPropertiesPersister 的 Javadoc 写道,“从 JDK 1.6 开始,Properties.load/store 也将用于读取器/写入器,有效地将此类转换为简单的向后兼容适配器” ,所以即使 Spring 也没有使用 Spring-only 方法......它使用 JDK 方法。你应该接受 Deh 的回答。
    • 注解中没有SPRING特有的方法,比如使用@value关键字从属性文件中读取参数?
    • @hirosht 我认为没有。这很糟糕,因为您似乎必须为使用动态参数的操作保留一个单独的文件。
    • 有没有办法知道从哪里读取和写回属性?还有没有办法写一个类,而不是指定道具?
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2014-07-13
    • 2011-11-13
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多