gpt4 book ai didi

java - 如何使用 groovy 读取文件并将其内容存储为变量?

转载 作者:行者123 更新时间:2023-11-30 06:55:49 24 4
gpt4 key购买 nike

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

#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") 可以读取整个文件并将其存储在一个变量中,但不能分开。任何帮助将不胜感激

最佳答案

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

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() 来应用值即可。

关于java - 如何使用 groovy 读取文件并将其内容存储为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com