使用 Groovy 从属性文件中获取值 [英] Get values from properties file using Groovy
问题描述
如何使用 Groovy 从属性文件中获取值?
How to get values from properties file using Groovy?
我需要一个属性文件 (.properties),它将文件名作为键,并将它们的目标路径作为值.我需要在运行时解析密钥,具体取决于需要移动的文件.
I require to have a property file (.properties) which would have file names as key, and their destination path as the value. I will need the key to be resolved at runtime, depending on file that needs to be moved.
到目前为止,我似乎能够加载属性,但无法从加载的属性中获取"值.
So far I am able to load the properties it seems but can't "get" the value from the loaded properties.
我提到了线程:groovy:如何访问属性文件? 和以下是我到目前为止的代码片段
I referred to the thread : groovy: How to access to properties file? and following is the code snippet i have so far
def props = new Properties();
File propFile =
new File('D:/XX/XX_Batch/XX_BATCH_COMMON/src/main/resources/patchFiles.properties')
props.load(propFile.newDataInputStream())
def config = new ConfigSlurper().parse(props)
def ant = new AntBuilder()
def list = ant.fileScanner {
fileset(dir:getSrcPath()) {
include(name:"**/*")
}
}
for (f in list) {
def key = f.name
println(props)
println(config[key])
println(config)
def destn = new File(config['a'])
}
属性文件现在有以下条目:
the properties file has the following entries for now :
jan-feb-mar.jsp=/XX/Test/1
XX-1.0.0-SNAPSHOT.jar=/XX/Test/1
a=b
c=d
如果我使用 props.getProperty('a') 查找,将返回正确的值或者,配置['a']还尝试了代码:notation
Correct values are returned if I look up using either props.getProperty('a') or, config['a'] Also tried the code: notation
但是一旦切换到使用变量key",就像在 config[key] 中一样,它返回 --> [:]
But as soon as switch to using the variable "key", as in config[key] it returns --> [:]
我是 groovy 的新手,不能说我在这里错过了什么.
I am new to groovy, can't say what am i missing here.
推荐答案
在我看来你把事情复杂化了太多.
It looks to me you complicate things too much.
这是一个应该可以完成工作的简单示例:
Here's a simple example that should do the job:
对于给定的 test.properties
文件:
a=1
b=2
此代码运行良好:
Properties properties = new Properties()
File propertiesFile = new File('test.properties')
propertiesFile.withInputStream {
properties.load(it)
}
def runtimeString = 'a'
assert properties."$runtimeString" == '1'
assert properties.b == '2'
这篇关于使用 Groovy 从属性文件中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!