How to read a file in Groovy into a string?

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?


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
}