如何使用Groovy从属性文件中获取值?
我需要一个属性文件(.properties),它将文件名作为键,并将其目标路径作为值.我需要在运行时解析密钥,具体取决于需要移动的文件.
到目前为止,我能够加载它看起来的属性,但不能从加载的属性"获取"值.
我提到了线程:groovy:如何访问属性文件?以下是我到目前为止的代码片段
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']) }
属性文件现在具有以下条目:
jan-feb-mar.jsp=/XX/Test/1 XX-1.0.0-SNAPSHOT.jar=/XX/Test/1 a=b c=d
如果我使用props.getProperty('a')或config ['a']查找,则返回正确的值.还尝试了代码:notation
但是一旦切换到使用变量"key",就像在config [key]中一样,它返回 - > [:]
我是groovy的新手,不能说我在这里失踪了什么.
除非File
是必要的,如果要加载的文件是src/main/resources
或者src/test/resources
文件夹或类路径,getResource()
是另一种方式来解决这个问题.
例如.
def properties = new Properties() //both leading / and no / is fine this.getClass().getResource( '/application.properties' ).withInputStream { properties.load(it) } //then: "access the properties" properties."my.key"
以防万一...
如果属性键包含点(.),请记住将键放在引号中.
属性文件:
a.x = 1
常规:
Properties properties ... println properties."a.x"
在我看来,你太复杂了.
这是一个应该完成工作的简单示例:
对于给定的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'