简体   繁体   English

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

[英]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')

The shortest way is indeed just最短的路确实只是

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

but in this case you have no control on how the bytes in the file are interpreted as characters.但在这种情况下,您无法控制文件中的字节如何解释为字符。 AFAIK groovy tries to guess the encoding here by looking at the file content. AFAIK groovy 试图通过查看文件内容来猜测这里的编码。

If you want a specific character encoding you can specify a charset name with如果你想要一个特定的字符编码,你可以指定一个字符集名称

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

See API docs on File.getText(String) for further reference.如需进一步参考,请参阅File.getText(String)上的 API 文档

A slight variation...一个细微的变化...

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

In my case new File() doesn't work, it causes a FileNotFoundException when run in a Jenkins pipeline job.在我的情况下, new File()不起作用,它在 Jenkins 管道作业中运行时会导致FileNotFoundException The following code solved this, and is even easier in my opinion:以下代码解决了这个问题,在我看来更容易:

def fileContents = readFile "path/to/file"

I still don't understand this difference completely, but maybe it'll help anyone else with the same trouble.我仍然不完全理解这种差异,但也许它会帮助其他有同样问题的人。 Possibly the exception was caused because new File() creates a file on the system which executes the groovy code, which was a different system than the one that contains the file I wanted to read.异常可能是因为new File()在执行常规代码的系统上创建了一个文件,该文件与包含我想要读取的文件的系统不同。

the easiest way would be最简单的方法是

new File(filename).getText()

which means you could just do:这意味着你可以这样做:

new File(filename).text

Here you can Find some other way to do the same.在这里你可以找到一些其他的方法来做同样的事情。

Read file.读取文件。

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

Read Full file.读取完整文件。

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

Read file 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)

}

Create a new file.创建一个新文件。

new File("C:\Temp\FileName.txt").createNewFile();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM