How to read a file in Groovy into a string?

FileGroovy

File Problem Overview


I need to read a file from the file system and load the entire contents into a string in a groovy controller, what's the easiest way to do that?

File Solutions


Solution 1 - File

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

If you need to specify the character encoding, use the following instead:

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

Solution 2 - File

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.

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.

Solution 3 - File

A slight variation...

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

Solution 4 - File

In my case new File() doesn't work, it causes a FileNotFoundException when run in a Jenkins pipeline job. 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.

Solution 5 - File

the easiest way would be

new File(filename).getText()

which means you could just do:

new File(filename).text

Solution 6 - File

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionraffianView Question on Stackoverflow
Solution 1 - FileDónalView Answer on Stackoverflow
Solution 2 - FilejaetzoldView Answer on Stackoverflow
Solution 3 - Filelinus1412View Answer on Stackoverflow
Solution 4 - FileP KuijpersView Answer on Stackoverflow
Solution 5 - FileReverend GonzoView Answer on Stackoverflow
Solution 6 - Fileshashi singhView Answer on Stackoverflow