如何在Groovy中读取文件到字符串?

我需要从文件系统中读取一个文件,并将整个内容加载到groovy控制器中的字符串中,最简单的方法是什么?

316711 次浏览

最简单的方法是

new File(filename).getText()

这意味着你可以这样做:

new File(filename).text
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
}

捷径确实是正义的

String fileContents = new File('/path/to/file').text

但是在这种情况下,您无法控制文件中的字节如何被解释为字符。AFAIK groovy试图通过查看文件内容来猜测这里的编码。

如果需要特定的字符编码,可以使用指定字符集名称

String fileContents = new File('/path/to/file').getText('UTF-8')

详见File.getText(String)上的API文档

在这里,你可以找到其他方法来做同样的事情。

读文件。

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();

在我的例子中,new File()不起作用,当在Jenkins管道作业中运行时,它会导致FileNotFoundException。下面的代码解决了这个问题,在我看来甚至更简单:

def fileContents = readFile "path/to/file"

我仍然不完全理解其中的区别,但也许它会帮助其他有同样麻烦的人。这个异常可能是因为new File()在执行groovy代码的系统上创建了一个文件,这个文件与包含我想要读取的文件的系统不同。