user5653362 user5653362 - 1 year ago 240
Groovy Question

Read from file and save in Property using groovy script

I am trying to read two values from a text file both values on a different line

for example:



This is what I tried:

def f = new File('/testdata.txt')
def records = f.readLines();

records.each {


But it is only setting the last value to both custom properties.

Answer Source

The problem is that your loop iterates two times, the first it assigns the first value to your IdOne and IdTwo properties, the second iteration overwrites both properties with the second value; due to this you've the last iteration value in your both properties. A possible solution as @user1708042 notes in the comments could be simply not iterate and set the values for your properties directly:

def f = new File('/testdata.txt') 
def records = f.readLines()

Another possible solutions could be to combine two lists; one with the property names and other one with the values in a Map, and then iterate over map entries setting the property name and the property values, for example:

def propertyName = ['IdOne','IdTwo']
def records = ['1234','5678'] // def records = new File('/testdata.txt').readLines()

def mapProperties = [propertyName,records].transpose().collectEntries()

mapProperties.each{ name, value ->
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download