How to read a file in Groovy into a string?

raffian picture raffian · Oct 11, 2011 · Viewed 262.2k times · Source

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?

Answer

Dónal picture Dónal · Oct 11, 2011
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')