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

本文介绍在Groovy中将文件内容读取并转换为字符串的多种方法,包括直接读取、指定字符编码读取及逐行读取等,适用于不同场景的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How to read a file in Groovy into a string?

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


#1楼

参考:https://stackoom.com/question/WQkA/如何将Groovy中的文件读入字符串


#2楼

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文档


#3楼

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. 读取文件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();

#4楼

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()在系统上创建了一个执行groovy代码的文件,这个系统与包含我想要读取的文件的系统不同。


#5楼

the easiest way would be 最简单的方法

new File(filename).getText()

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

new File(filename).text


#6楼

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

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

String fileContents = new File('/path/to/file').getText('UTF-8')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值