Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

Get values from properties file using Groovy

How to get values from properties file using Groovy?

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.

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

Correct values are returned if I look up using either props.getProperty('a') or, config['a'] Also tried the code: notation

But as soon as switch to using the variable "key", as in config[key] it returns --> [:]

I am new to groovy, can't say what am i missing here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks to me you complicate things too much.

Here's a simple example that should do the job:

For given test.properties file:

a=1
b=2

This code runs fine:

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...