2

I'm trying to read values from text files and putting the values into the list using the below method.

def myKeys = []
new File( '/tmp/A.txt' ).eachLine { line ->
    myKeys << line
}

def myValues = []
new File( '/tmp/B.txt' ).eachLine { line ->
    myValues << line
}

Problem is, Jenkins doesn't allow this to run on a slave and I'm not sure how to use readFile method here because it doesn't solve the purpose. I want to create a List, which readFile couldn't do.

1 Answer 1

3

You can get the same result using readFile step. It reads a given file from your workspace and returns the content of the file as a string. Then you can use String.eachLine(closure) method to iterate every line and add it to the list you expect. Keep in mind one thing, however - if you want to use String.eachLine() method, you need to do it in the @NonCPS mode. Otherwise, you will get maybe a single element from the iteration at best.

Take a look at the following example:

pipeline {
    agent any

    stages {
        stage("Read test.txt file") {
            steps {
                script {
                    final String content = readFile(file: "test.txt")
                    final List myKeys = extractLines(content)
                    echo "myKeys = ${myKeys}"
                }
            }
        }
    }
}

@NonCPS
List extractLines(final String content) {
    List myKeys = []
    content.eachLine { line -> 
        myKeys << line
    }
    return myKeys
}

In this example, we use simple test.text file with the following content:

$ cat test.txt 
123
qwe
asd
zxc

Running this exemplary pipeline produces the following output:

Running on Jenkins in /home/wololock/.jenkins/workspace/jobA
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Read test.txt file)
[Pipeline] script
[Pipeline] {
[Pipeline] readFile
[Pipeline] echo
myKeys = [123, qwe, asd, zxc]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

You could use a similar approach to extract keys and values from two different files, e.g.

def myKeys = extractLines(readFile(file:"/tmp/A.txt"))
def myValues = extractLines(readFile(file:"/tmp/B.txt"))
2
  • Do we need to close something after readFile, or is that automatically handled for us? I'm surprised this doesn't seem to be documented anywhere... May 12, 2021 at 16:24
  • final String body = readFile(file: "/tmp/output.text") ..... is giving java.nio.file.NoSuchFileException: /tmp/output.text ...... Jan 6 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.