How to read a file in Groovy into a string?

294,550

Solution 1

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

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

A slight variation...

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

Solution 4

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

the easiest way would be

new File(filename).getText()

which means you could just do:

new File(filename).text
Share:
294,550
raffian
Author by

raffian

Applications architect and code slinger since 2000, my background is full stack Java. Reach me at 72616666692e6970616440676d61696c2e636f6d My other passion is landscape photography, check it out if you're interested!

Updated on July 23, 2021

Comments

  • raffian
    raffian almost 3 years

    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?