Jenkinsfile:创建一个新文件(Groovy)

Omr*_*mri 1 groovy jenkins jenkins-groovy jenkins-pipeline

我正在尝试编写一个Jenkinsfile带有创建新文件并稍后使用的阶段。

无论我做什么,我都会收到以下错误:

java.io.FileNotFoundException: ./ci/new_file.txt (No such file or directory)
Run Code Online (Sandbox Code Playgroud)

这是相关的代码块:

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

我回顾了一些类似的问题,到目前为止没有任何帮助。请指教。

gro*_*gor 5

您实际上还没有创建该文件并尝试阅读此文件。您必须在使用它之前创建文件。例如:

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

但这不是您的最佳解决方案。最好使用詹金斯步骤“readFile”和“writeFile”。文档在这里 - https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/ 例如:

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"
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的评论。您的第一个示例不起作用(我得到:“java.io.IOException:没有这样的文件或目录”)。您的第二个示例效果不佳(我得到:“预期的命名参数,但得到了 [new_file.txt,一些文本]”)。语法应该是:`writeFile file: "./ci/new_file.txt", text: "Some Text"` 并且它按预期工作。 (2认同)