【问题标题】:How to read file using groovy and store its contents are variables?如何使用 groovy 读取文件并将其内容存储为变量?
【发布时间】:2016-04-27 21:56:24
【问题描述】:

我正在寻找特定的方式来读取文件并将其内容存储为不同的变量。我的属性文件示例:

#Local credentials:
postgresql.url = xxxx.xxxx.xxxx
postgresql.username = xxxxxxx
postgresql.password = xxxxxxx
console.url = xxxxx.xxxx.xxx

目前我正在使用这个 java 代码来读取文件并使用变量:

  Properties prop = new Properties();
  InputStream input = null;

  try {
            input = new FileInputStream("config.properties");
            prop.load(input);
            this.postgresqlUser = prop.getProperty("postgresql.username")
            this.postgresqlPass = prop.getProperty("postgresql.password")
            this.postgresqlUrl = prop.getProperty("postgresql.url")
            this.consoleUrl = prop.getProperty("console.url")

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
    }

我的同事建议使用 groovy 方法来处理这个问题并提到了流,但我似乎找不到太多关于如何将数据存储在单独变量中的信息,目前我所知道的是 def text = new FileInputStream("config.properties").getText("UTF-8") 可以读取整个文件并将其存储在一个变量中,但不能分开。任何帮助将不胜感激

【问题讨论】:

标签: java groovy readfile


【解决方案1】:

如果您愿意让您的属性文件键和类属性遵守命名约定,那么您可以很容易地应用属性文件值。这是一个例子:

def config = '''
#Local credentials:
postgresql.url = xxxx.xxxx.xxxx
postgresql.username = xxxxxxx
postgresql.password = xxxxxxx
console.url = xxxxx.xxxx.xxx
'''

def props = new Properties().with {
    load(new StringBufferInputStream(config))
    delegate
}

class Foo {
    def postgresqlUsername
    def postgresqlPassword
    def postgresqlUrl
    def consoleUrl

    Foo(Properties props) {
        props.each { key, value ->
            def propertyName = key.replaceAll(/\../) { it[1].toUpperCase() }
            setProperty(propertyName, value)
        }
    }
}

def a = new Foo(props)

assert a.postgresqlUsername == 'xxxxxxx'
assert a.postgresqlPassword == 'xxxxxxx'
assert a.postgresqlUrl == 'xxxx.xxxx.xxxx'
assert a.consoleUrl == 'xxxxx.xxxx.xxx'

在本例中,属性键通过删除 '.' 进行转换。并将以下字母大写。所以postgresql.url 变成了postgresqlUrl。然后只需遍历键并调用setProperty() 来应用值即可。

【讨论】:

    【解决方案2】:

    【讨论】:

    • 同意。 ConfigSlurper 是使用传统 Java 属性文件的更好选择。让它变得轻而易举。
    猜你喜欢
    • 1970-01-01
    • 2016-11-26
    • 2021-03-02
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2017-11-05
    相关资源
    最近更新 更多