无法读取jenkins目录中的文件

ffvjumwh  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(531)

我正试图读取Jenkins管道中的一个文件。我使用linux'tee'命令创建这个文件。我尝试使用内置的java函数读取文件,例如java.nio中的files.readalllines或java.io包中的bufferedreader。两种情况都不起作用。
我之所以要使用这两种方法或类似的技术,是因为我必须在共享库中读取此文件,而不是在jenkins文件中读取。我尝试读取jenkins管道中的文件,以测试这两种方法是否有效。
如何使用这些技术读取工作区中已有的文件?
另外,我尝试使用jenkins readfile方法,它可以工作,但我想我不能在我的共享库中使用它。
我的Jenkins档案是:

import java.io.file.*

pipeline {
agent any

stages {
    stage('Scan Timeout Test') {
        steps {
            script {
                sh '''echo "Running ls before ..."
ls -lt
                '''
                sh 'ls -lt | tee lslog.txt'
                sh '''pwd
                ls -lt
                '''
                getLogs("$WORKSPACE/lslog.txt")
            }
        }
    } //end of stage
  }
}

def getLogs(logPath) throws IOException {
    //println "Reading $logPath..."
    //def text = readFile logPath
    //println text
     /*println "[INFO] Reading Log File: " + Paths.get(logPath).toAbsolutePath().toString()
     try {
       return Files.readAllLines(Paths.get(logPath), StandardCharsets.UTF_8);
     } catch(IOException e){
         println "[ERROR] Failed to read file '"+logPath+"': "+e.getMessage()
         throw e
     }*/
     BufferedReader bufReader = new BufferedReader(new FileReader(logPath)); 
     ArrayList<String> listOfLines = new ArrayList<>(); 

     String line = bufReader.readLine(); 

     while (line != null) { 
         listOfLines.add(line); 
         line = bufReader.readLine(); 
     }

     bufReader.close();
     return listOfLines
}

The output that I get in my Jenkins console is: 
+ pwd
/jenkins/workspace/test
+ ls -lt
total 44
-rw-r--r-- 1 root root   526 Aug 21 11:32 lslog.txt
drwxr-xr-x 2 root root   173 Aug 21 11:32 vars
drwxr-xr-x 3 root root   109 Aug 21 11:32 resources
drwxr-xr-x 4 root root    29 Aug 21 11:32 src
-rw-r--r-- 1 root root 22783 Aug 21 11:32 README.md
-rw-r--r-- 1 root root   602 Aug 21 11:32 build.gradle
drwxr-xr-x 3 root root    21 Aug 21 11:32 gradle
-rw-r--r-- 1 root root  5296 Aug 21 11:32 gradlew
-rw-r--r-- 1 root root  2176 Aug 21 11:32 gradlew.bat
drwxr-xr-x 2 root root   118 Aug 21 11:32 integration-tests
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.io.FileNotFoundException: /jenkins/workspace/test/lslog.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)

使用ls-lt,我可以看到我的文件lslog.txt是在目录中创建的,但我无法读取它。

e0bqpujr

e0bqpujr1#

您可以在共享库中使用readfile,只要您传递这些步骤。查看文档https://www.jenkins.io/doc/book/pipeline/shared-libraries/#accessing-步骤

package org.foo
class bar {
  static void readFile(filePath, steps) {
    def text = steps.readFile(file: filePath)
  }
}

相关问题