我正在寻找一种常规的特定方法来读取文件并将其内容存储为不同的变量。我的属性文件示例:
#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) {
}
}
}
}
我的同事建议使用常规方式来处理这个问题并提到了流,但我似乎找不到太多有关如何将数据存储在单独变量中的信息,到目前为止我所知道的是 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/