【问题标题】:Save changes to Property File in Grails在 Grails 中保存对属性文件的更改
【发布时间】:2023-03-30 00:17:01
【问题描述】:

我有一个从属性文件中读取的 grails 应用程序。我创建了一个管理页面,允许用户查看此文件中的设置。我想允许用户更新各种属性并使用 Grails 将它们保存回属性文件。

我的问题是我似乎无法弄清楚如何将更改保存回属性文件。

这是我从文件中读取并更改属性的代码:

  def env = params.getAt("environment");
    if (env != null){
     //Read from Property file based on user selection
        def props = new Properties()
        def cl = Thread.currentThread().contextClassLoader
        def filepath = env+'.properties'
        props.load  servletContext.getResourceAsStream("/WEB-INF/"+ filepath)

        Enumeration e = props.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            def input = params.getAt(key)
            if (input != null){
                props.setProperty(key,input)
            }
        }
         //props.store(propFile.newWriter(), null)

    }

关于如何保存/覆盖 /WEB-INF/example.properties 中的 example.properties 文件的任何想法?

【问题讨论】:

    标签: spring grails groovy grails-2.0


    【解决方案1】:

    我认为您可能正在寻找 ServletContext 中的 getRealPath 方法 http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

    简单的例子告诉你如何使用它

    http://82.157.70.109/mirrorbooks/javaservletjspcookbook/0596005725_jsvltjspckbk-chp-14-sect-7.html
    

    【讨论】:

    • 您发布的链接似乎无效。所以我需要使用获取真实路径但我不需要通过输出流写回属性文件吗?不知道如何在 groovy/grails 中做
    • 如果你得到了比方说 web-inf 的真实路径,那么你可以找到文件的绝对路径,然后你可以像在普通 Java 中一样使用 properties.store 打开一个输出流(参见 java .util.Properties javadoc)例如...我希望它有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多