54

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.

Community
  • 1
  • 1
user3151610
  • 637
  • 1
  • 5
  • 12
  • 1
    Tip: There is no such thing as a 'Java' properties file. It is either a properties file, or it isn't. It does not matter which language (or text editor) wrote it. – Andrew Thompson Jan 01 '14 at 18:08
  • 3
    possible duplicate of [Parse a properties file with groovy](http://stackoverflow.com/questions/16852264/parse-a-properties-file-with-groovy) – tim_yates Jan 01 '14 at 18:31
  • @tim_yates Thank you. I had seen that thread. thats not it :( – user3151610 Jan 01 '14 at 20:32

8 Answers8

135

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'
JBaruch
  • 22,610
  • 5
  • 62
  • 90
  • Thank you for your response. The thing is : 1. the file is going to have a lot of entries 2. i want to not have all the key/ value written as asserts in the groovy script. can i not have the key be resolved at run time ? and the value picked accordingly from the properties. the key will be based ob file names i read and they can 1, or more from about a few hundred (and i really need to remember that pressing 'enter' here submits my comment) – user3151610 Jan 01 '14 at 19:53
  • 3
    The asserts are just to show that it works. Of course you don't need them in your code. Added a comment in the answer. – JBaruch Jan 01 '14 at 19:54
  • 1
    Thank you @JBaruch I am not clear enough in asking i realize :) My concern is about how to get the ".a" part to be dynamic ? "a" is an example , its going to be a big key string that i will be getting from a file name . How can i append a variable to "properties" for eg . can i write ? - assert properties.xyz == '/isekk/123456' where xyz is a variable holding some string. my code snippet above elaborates ths scenario. Appreciate you taking time to reply. – user3151610 Jan 01 '14 at 20:30
  • 2
    got it. Example changed. – JBaruch Jan 01 '14 at 21:05
  • I think he wants to know a way to list all keys in property file, which he wants to iterate later. – Jan Pešta Mar 26 '19 at 10:30
  • is it possible to do the same thing but reading a ".INI"? this is because I work with PYTHON which reads .INI with sections, but I haven't found that groovy can do it – SeWaNsX Aug 16 '22 at 17:46
11

Unless File is necessary, and if the file to be loaded is in src/main/resources or src/test/resources folder or in classpath, getResource() is another way to solve it.

eg.

    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"
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • this works, though it's not the same with and without "/" ava.lang.NullPointerException: Cannot invoke method withInputStream() on null object – Pablo Pazos Feb 09 '22 at 21:09
6

Had a similar problem, we solved it with:

def content = readFile 'gradle.properties'

Properties properties = new Properties()
InputStream is = new ByteArrayInputStream(content.getBytes());
properties.load(is)

def runtimeString = 'SERVICE_VERSION_MINOR'
echo properties."$runtimeString"
SERVICE_VERSION_MINOR = properties."$runtimeString"
echo SERVICE_VERSION_MINOR
user3265317
  • 166
  • 2
  • 8
  • This works well in Jenkins pipeline scripts, but not in plain Groovy as readFile etc is not available. Furthermore, if running in Jenkins already, I'd tend to use the 'readProperties' method to not deal with the input streams directly and having a self explanatory one-liner instead. – bully Jan 14 '21 at 10:09
5

Just in case...

If a property key contains dot (.) then remember to put the key in quotes.

properties file:

a.x = 1

groovy:

Properties properties ...

println properties."a.x"
Łukasz Dumiszewski
  • 2,888
  • 2
  • 21
  • 13
1
Properties properties = new Properties()

properties.load(new File("path/to/file.properties").newReader())
RobC
  • 22,977
  • 20
  • 73
  • 80
0

Just another way of doing it. Use this if it works for you. :)

Properties properties = new Properties()

//loading property file

File propertiesFile = new File(this.class.getResource('application.properties').getPath())

propertiesFile.withInputStream {

    properties.load(it)

}

//Accessing the value from property file

properties.getProperty('userName')
JustSomeGuy
  • 3,677
  • 1
  • 23
  • 31
Vic Key
  • 37
  • 4
-1

With static method extension:

Properties.metaClass.static.fromFile =
    {file -> new Properties().with{new File(file).withInputStream it.&load;it}}

def properties = Properties.fromFile('test.properties')
plajko
  • 381
  • 2
  • 9
-1

Groovy for getting value of property from "local.properties" by giving key.

Example- For finding value of this property's key is "mail.smtp.server"

In V5

ctx.getBean("configurationService")

configurationService = ctx.getBean("configurationService")

String value = configurationService.getConfiguration().getString("mail.smtp.server","")

In 1905

spring.getBean("configurationService")

configurationService = spring.getBean("configurationService")

String value = configurationService.getConfiguration().getString("mail.smtp.server","")

Priyanka Gupta
  • 339
  • 2
  • 4