如何在Groovy中将文件读入字符串?

ldfqzlk8  于 4个月前  发布在  其他
关注(0)|答案(6)|浏览(40)

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

puruo6ea

puruo6ea1#

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

字符串
如果需要指定字符编码,请改用以下代码:

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

mzaanser

mzaanser2#

最短的路确实是公正的

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

字符串
但是在这种情况下,你无法控制文件中的字节如何被解释为字符。AFAIK groovy试图通过查看文件内容来猜测这里的编码。
如果需要特定的字符编码,可以使用

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


有关更多参考,请参阅File.getText(String)上的API文档。

1u4esq0p

1u4esq0p3#

一个微小的变化...

new File('/path/to/file').eachLine { line ->
  println line
}

字符串

brgchamk

brgchamk4#

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

def fileContents = readFile "path/to/file"

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

wvmv3b1j

wvmv3b1j5#

最简单的方法就是
第一个月
这意味着你可以这样做:

new File(filename).text

字符串

j0pj023g

j0pj023g6#

在这里你可以找到一些其他的方法来做同样的事情。
读取文件。

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

相关问题