write - How to read a file in Groovy into a string?

jenkins groovy read file (4)

A slight variation...

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

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?

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

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.