【发布时间】:2011-12-05 11:17:28
【问题描述】:
我需要从文件系统中读取文件并将整个内容加载到 groovy 控制器中的字符串中,最简单的方法是什么?
【问题讨论】:
我需要从文件系统中读取文件并将整个内容加载到 groovy 控制器中的字符串中,最简单的方法是什么?
【问题讨论】:
String fileContents = new File('/path/to/file').text
如果您需要指定字符编码,请改用以下代码:
String fileContents = new File('/path/to/file').getText('UTF-8')
【讨论】:
File 对象来自一个普通的java jar,这也是可行的。我不确定Groovy 是否有自己的特殊File 类和text 属性,但似乎File 对象来自哪里并不重要,它是否由Groovy 代码实例化或 Java 代码。
最短的路确实只是
String fileContents = new File('/path/to/file').text
但在这种情况下,您无法控制文件中的字节如何解释为字符。 AFAIK groovy 尝试通过查看文件内容来猜测此处的编码。
如果你想要一个特定的字符编码,你可以指定一个字符集名称
String fileContents = new File('/path/to/file').getText('UTF-8')
请参阅API docs on File.getText(String) 以获取更多参考。
【讨论】:
someFile.text 不会做出明智的猜测,它只是使用平台默认编码(在现代 Linux 上通常为 UTF-8,但在 Windows/Mac OS 上类似于 windows-1252 或 MacRoman,除非你用它覆盖它-Dfile.encoding=...)
略有不同...
new File('/path/to/file').eachLine { line ->
println line
}
【讨论】:
在我的情况下,new File() 不起作用,它在 Jenkins 管道作业中运行时会导致 FileNotFoundException。以下代码解决了这个问题,在我看来更容易:
def fileContents = readFile "path/to/file"
我仍然不完全理解这种差异,但也许它会帮助其他遇到同样麻烦的人。可能是因为new File() 在执行 groovy 代码的系统上创建了一个文件,该文件与包含我要读取的文件的系统不同。
【讨论】:
String fp_f = readFile("any_file") if (fp.length()) { currentBuild.description = fp } 另外,如果找不到文件,则会出现错误。
【讨论】:
您可以在这里找到其他方法来做同样的事情。
读取文件。
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();
读取文件 Line Bye Line.
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();
【讨论】:
def。