Omri
Omri

Reputation: 1656

Jenkinsfile: Create a new file (Groovy)

I'm trying to write a Jenkinsfile with a stage that create a new file and use it later.

Whatever i do i get the following error:

java.io.FileNotFoundException: ./ci/new_file.txt (No such file or directory)

Here is the relevant code block:

pipeline {
    agent any
    stages {
        stage('Some Stage') {
            steps {
                script{
                    file = new File('./ci/new_file.txt').text
                    file.createNewFile()
                }
            }
        }
    }
}

I went over some similar questions and nothing has helped so far. Please advise.

Upvotes: 2

Views: 13653

Answers (3)

DevEzro
DevEzro

Reputation: 87

I answered a similiar question a time ago. Here it is my answered code. Hope it can help you!

stage('My Stage'){
      steps{
            ...
            script{
                   writeFile file: 'groovy1.txt', text: 'Working with files the Groovy way is easy.'
                   sh 'ls -l groovy1.txt'
                   sh 'cat groovy1.txt' 
            }
       }
    }

Upvotes: -1

grolegor
grolegor

Reputation: 1330

You have not actually created the file and tried to read this one. You have to create file before using it. For example:

pipeline {
    agent any
    stages {
        stage('Some Stage') {
            steps {
                script {
                    File file = new File('./ci/new_file.txt')
                    file.createNewFile()
                    //...
                    String fileText = ... read file
                }
            }
        }
    }
}

But this is not the best solution for you. It is better to use jenkins steps 'readFile' and 'writeFile'. Documentation is here - https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/ For example:

pipeline {
    agent any
    stages {
        stage('Some Stage') {
            steps {
                script {
                    writeFile file: "./ci/new_file.txt", text: "Some Text"
                    //...
                    String fileText = readFile file: "./ci/new_file.txt"
                }
            }
        }
    }
}

Upvotes: 5

lichensky
lichensky

Reputation: 66

Is your pipeline code executed on remote agent?

Cloudbees notes that java.io.File may not work in Pipeline and recommends using native pipeline steps to interact with files.

https://support.cloudbees.com/hc/en-us/articles/230922128-Pipeline-Using-java-io-File-in-a-Pipeline-description

Upvotes: 0

Related Questions