Search code examples
jenkinsgroovydevops

Groovy read file line by line and store it into list


I have a file called apps.txt which has three app names in it

frontendapp

authorizationservice

connectorservice*

In jenkins pipeline i want to perform some operation on them one by one so i am trying to get them in groovy list using this code -

                    list = readFile.readFileLineByLine("${workspace}/apps.txt").collect {it}
                    for (item in list) {
                        println "I need to perform some operations on files"
                    }

But getting groovy.lang.MissingPropertyException. If i use file class like this - list = new File("${workspace}/apps.txt").collect {it} then it search for a file on Jenkins master node only and i get fileNotFoundException.

If i use list = readFile("${workspace}/apps.txt").collect {it} then list gets values character by character. How i can get app names from apps.txt inorder to perform operation on each app.


Solution

  • Your attempts are close, but mix things up.

    Those are working ways:

    def list = new File("${workspace}/apps.txt").text.readLines()
    

    Note the .text call inbetween.

    def list = readFile("${workspace}/apps.txt").readLines()
    

    Or with the helper Jenkins provides.

    Side note: .collect{it} is just .collect() - and usually is only needed to copy a list. Since the read lines from the file are already eagerly read, those are copies.