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

raf*_*ian 297 groovy file

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

Dón*_*nal 488

String fileContents = new File('/path/to/file').text
Run Code Online (Sandbox Code Playgroud)

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

String fileContents = new File('/path/to/file').getText('UTF-8')
Run Code Online (Sandbox Code Playgroud)

  • 而已?jeez,我觉得自己像个白痴一样,谢谢 (64认同)
  • 这就是Groovy的美丽:) (6认同)
  • @dasKeks我认为可以安全地假设此方法的实现关闭了所有必要的资源.无论如何,您无法访问可能创建的任何阅读器,因此您*不能*关闭它 (6认同)
  • @roens 这没有意义。我怀疑其中还有其他一些因素,比如您有一个隐藏字段或类似内容的局部变量。 (3认同)

小智 77

最短的路确实是公正的

String fileContents = new File('/path/to/file').text
Run Code Online (Sandbox Code Playgroud)

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

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

String fileContents = new File('/path/to/file').getText('UTF-8')
Run Code Online (Sandbox Code Playgroud)

有关进一步参考,请参阅API文档File.getText(String).

  • +1用于推荐采用编码参数的版本.简单的`someFile.text`并不是一个聪明的猜测,它只是使用平台默认编码(在现代Linux上通常是UTF-8,但在Windows/Mac OS上类似于windows-1252或MacRoman,除非你被覆盖它与`-Dfile.encoding = ...`) (7认同)

小智 50

略有变化......

new File('/path/to/file').eachLine { line ->
  println line
}
Run Code Online (Sandbox Code Playgroud)

  • 这不会将文件内容读入变量 (5认同)
  • 是的,但它仍然是一个有用的习惯,捕捉"为记录". (5认同)

Rev*_*nzo 12

最简单的方法

new File(filename).getText()

这意味着你可以这样做:

new File(filename).text


P K*_*ers 10

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

def fileContents = readFile "path/to/file"
Run Code Online (Sandbox Code Playgroud)

我仍然不完全了解这种区别,但是也许会对其他有同样麻烦的人有所帮助。可能是由于new File()在系统上创建了一个执行常规代码的文件而导致的异常,该文件与包含我要读取的文件的系统不同。

  • 适用于詹金斯。因为 readFile 是一个内部关键字,不需要 jenkins-admin 的任何导入或额外批准。整个文件可以在 String var 中读取,然后通过以下代码打印:`String fp_f = readFile("any_file") if (fp.length()) { currentBuild.description = fp }` 另外,如果找不到文件,则有错误。 (3认同)
  • 顺便提一句。这样做的原因是, new File() 会在您的计算机上查找文件,就像 Jenkins 中的 readFile 会在 java vm 的常规沙箱中查找您的管道内容可能正在运行的地方一样......此外,您还可以在沙箱中使用 readfile管道,但默认情况下不允许使用 File(),文件必须在 Jenkins 设置中列入白名单才能使用它。 (3认同)

sha*_*ngh 5

在这里您可以找到一些其他方法来执行相同的操作。

读取文件。

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();
Run Code Online (Sandbox Code Playgroud)

阅读完整文件。

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();
Run Code Online (Sandbox Code Playgroud)

逐行读取文件。

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)

}
Run Code Online (Sandbox Code Playgroud)

创建一个新文件。

new File("C:\Temp\FileName.txt").createNewFile();
Run Code Online (Sandbox Code Playgroud)