[英]How to read a file in Groovy into a string, without knowing the path to the file?
[英]How to read a file in Groovy into a string?
我需要从文件系统中读取一个文件并将整个内容加载到 groovy 控制器中的字符串中,最简单的方法是什么?
String fileContents = new File('/path/to/file').text
如果您需要指定字符编码,请改用以下内容:
String fileContents = new File('/path/to/file').getText('UTF-8')
最短的路确实只是
String fileContents = new File('/path/to/file').text
但在这种情况下,您无法控制文件中的字节如何解释为字符。 AFAIK groovy 试图通过查看文件内容来猜测这里的编码。
如果你想要一个特定的字符编码,你可以指定一个字符集名称
String fileContents = new File('/path/to/file').getText('UTF-8')
如需进一步参考,请参阅File.getText(String)
上的 API 文档。
一个细微的变化...
new File('/path/to/file').eachLine { line ->
println line
}
在我的情况下, new File()
不起作用,它在 Jenkins 管道作业中运行时会导致FileNotFoundException
。 以下代码解决了这个问题,在我看来更容易:
def fileContents = readFile "path/to/file"
我仍然不完全理解这种差异,但也许它会帮助其他有同样问题的人。 异常可能是因为new File()
在执行常规代码的系统上创建了一个文件,该文件与包含我想要读取的文件的系统不同。
在这里你可以找到一些其他的方法来做同样的事情。
读取文件。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.