我需要从文件系统中读取一个文件,并将整个内容加载到groovy控制器中的字符串中,最简单的方法是什么?
当前回答
在我的情况下,新文件()不工作,它导致FileNotFoundException运行在Jenkins管道作业。下面的代码解决了这个问题,在我看来甚至更简单:
def fileContents = readFile "path/to/file"
我仍然不完全理解其中的区别,但也许它会帮助其他有同样麻烦的人。这个异常可能是因为new File()在执行groovy代码的系统上创建了一个文件,而这个文件与包含我想要读取的文件的系统不同。
其他回答
最简单的方法是
新文件(filename) getText()。
这意味着你可以这样做:
new File(filename).text
在这里,你可以找到其他方法来做同样的事情。
读文件。
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();
阅读完整文件。
File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();
逐行读取文件。
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
log.info file1.readLines().get(i)
}
创建一个新文件。
new File("C:\Temp\FileName.txt").createNewFile();
在我的情况下,新文件()不工作,它导致FileNotFoundException运行在Jenkins管道作业。下面的代码解决了这个问题,在我看来甚至更简单:
def fileContents = readFile "path/to/file"
我仍然不完全理解其中的区别,但也许它会帮助其他有同样麻烦的人。这个异常可能是因为new File()在执行groovy代码的系统上创建了一个文件,而这个文件与包含我想要读取的文件的系统不同。
String fileContents = new File('/path/to/file').text
如果你需要指定字符编码,请使用下面的代码:
String fileContents = new File('/path/to/file').getText('UTF-8')
略有变化……
new File('/path/to/file').eachLine { line ->
println line
}