java如何使用groovy读取文件并将其内容存储为变量?
我正在寻找groovy特有的方法来读取文件并将其内容存储为不同的变量。我的属性文件示例:
#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")
可以读取整个文件并将其存储在一个变量中,但不能单独存储。任何帮助都将不胜感激
# 1 楼答案
看看ConfigSlurper:
http://mrhaki.blogspot.de/2009/10/groovy-goodness-using-configslurper.html
# 2 楼答案
如果您愿意使属性文件键和类属性遵守命名约定,那么可以非常轻松地应用属性文件值。下面是一个例子:
在本例中,通过删除“.”来转换属性键并将下面的字母大写。所以
postgresql.url
变成了postgresqlUrl
。然后,只需迭代键并调用setProperty()
来应用值